0

I can't find the reason why map lambda doesn't work when I apply it to a list of objects, for example:

class test():
    def __init__(self, input):
        self.input =input

    def print_intput(self):
        print(self.input)

objectlist=[]
for count in list(range(1,6)):
    objectlist.append(test(count))


for ob in objectlist:
    ob.print_intput()
"""
This ouputs:
1
2
3
4
5

"""
map(lambda x: x.print_intput(), objectlist)
"""
This has no output
"""

Why is the first output method works, simple for loop, and the map(lambda method doesn't work in this case).

Flying Turtle
  • 182
  • 5
  • 18

1 Answers1

2

map returns an iterator, when you iterate over it the lambda will be called on each element in the list one at a time and return the result.

Passing it to list will consume the iterator and give you output

list(map(lambda x: x.print_intput(), objectlist))
Iain Shelvington
  • 18,267
  • 22
  • 35
  • (since the OP wrote the redundant pattern `for i in list(range(...)): ` and this is directly related to this answer, you could expand this answer to talk about that as well - what do you say?) – jsbueno Apr 01 '20 at 01:26
  • For future reference, it should be noted that here, the generated list will be `[None, None, None, None, None]` as `print_input()` does not return anything. – XPhyro Apr 01 '20 at 01:33
  • The solution proposed by Iain Shelvington only returns None which obviously isn't the goal. However adding "list" in the other example where they use functions and not classes does work. the only solution I found was simply to use a for loop. Still not sure why map lambda doesn't work thought. – Flying Turtle Apr 09 '20 at 01:58
  • @Karl Knechtel I do not understand why my question was closed, I went through the other examples, making it a list isn't the solution as proposed in the other examples. – Flying Turtle Apr 09 '20 at 02:07