0

I want to define a class method which applies a different class method to a list - I thought the below would work but it doesn't seem to, am I missing something obvious?

class Foo():

    def __init__(self):
          pass

    def method1(self, data):
        do some stuff

    def method2(self, iterable):
        map(self.method1, iterable)
        do some more stuff

As a concrete example, method2 is applying method1 to each element of a list but the actual content of method1 (printing) doesn't seem to be executing:

class Foo():
    
    def __init__(self):
        self.factor = 2
        
    def method1(self, num):
        print(num*self.factor)
        
    
    def method2(self, ls):
        map(self.method1, ls)

f = Foo()
f.method2([1,2,3])

I would expect this to print 2, 4, 6 but nothing is printed.

5
  • I think you are making confusion with class methods and (instance) methods... I think you mean the latter one Commented Nov 26, 2021 at 9:21
  • Could you expand on "doesn't seem to [work]"? Give a minimal reproducible example. Commented Nov 26, 2021 at 9:23
  • @jonrsharpe sorry for ambiguity, have added dumb toy example - I would expect f.method2([1,2,3]) to print [2,4,6] but although the code runs nothing is printed Commented Nov 26, 2021 at 9:44
  • 1
    Then the answer below is correct - map is lazy. Commented Nov 26, 2021 at 9:46
  • ahhhh, yeah that make sense. Thank you! Commented Nov 26, 2021 at 9:47

1 Answer 1

1

map returns a generator (in Python 3), so you still need to iterate over it:

def method2(self, iterable):
    for val in map(self.method1, iterable):
        do some stuff with val

If you don't care about the return values, you could always just wrap it in a list: list(map(self.method1, iterable)).

Sign up to request clarification or add additional context in comments.

1 Comment

A list comprehension would be e.g. [self.method1(value) for value in iterable], but using a list/list comprehension for side effects isn't idiomatic - you're building a list you don't need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.