-1
re = [2, 3, 4, 5, 6, 7, 8]
result = []
a=list(map(lambda n:result.append(n), [i for i in re if i>5]))
print(result)
print(a)

If you run the above code, the value of result comes out correctly

re = [2, 3, 4, 5, 6, 7, 8]
result = []
a=list(map(lambda n:result.append(n), [i for i in re if i>5]))
print(result)
print(a)

The value of the result changes depending on whether the list is wrapped in a map or not, but I wonder why.

I expected a value to be added to result, but it is not added unless I wrap it in a list.

최윤석
  • 3
  • 1

1 Answers1

0

map() is a generator and is not processed until exercised. Try:

re = [2, 3, 4, 5, 6, 7, 8]
result = []
map_result = map(lambda n:result.append(n), [i for i in re if i>5])
print(result)
next(map_result)
print(result)

You will see that getting the first result from the mapping via next() has begun to populate the list result. You can call next(a) again and see that result would then have two items and so on...

When you call list() on a generator, you get "all the results" from it and exhaust it. Thus calling list() populates result with the three items.

Note that append() does not return a value (implied return of None) and thus the variable a in your code will be [None, None, None].

This use of map() is not pythonic and calling map for side effects should be avoided for the same reasons that comprehensions for side effects should be avoided.

See Also: Is it Pythonic to use list comprehensions for just side effects?

JonSG
  • 10,542
  • 2
  • 25
  • 36