Losing map value in variable

Question:

Can’t understand why I can’t assign map result to a variable. It’s losing its value.

>>> L = 'something'
>>> R = map(lambda x: x * 2, L)
>>> print(list(R))
['ss', 'oo', 'mm', 'ee', 'tt', 'hh', 'ii', 'nn', 'gg']
>>> V = list(R)
>>> print(V)
[]
Asked By: John Doe

||

Answers:

Because the map object can be iterated over only once. When you print it, that’s it. The next time you assign it, it’s empty

Instead, try

R = map(..)
V = list(R)
print(V)
Answered By: blue_note

In Python 3 map returns an iterator that, once consumed, will yield nothing.
In your case you are consuming it in the first print(list(R)) call, so in the second one it yields nothing which is the same as list() alone.

Answered By: Netwave
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.