map in Python 3 vs Python 2

Question:

I’m a Python newbie reading an old Python book. It’s based on Python 2, so sometimes I got little confused about detail.

There is a code

L=map(lambda x:2**x, range(7))

so it doesn’t return the list in python 3, and I googled it and found that list(L) works.
But the problem is, first list(L) works fine,
but when I use it again,

list(L)

list(L)

second one returns [ ]

Can somebody explain me what’s happening?

Asked By: Septacle

||

Answers:

map returns an iterator. As such, its output may only be used once. If you wish to store your results in a list, in the same way as Python 2.x, simply call list when you use map:

L = list(map(lambda x:2**x, range(7)))

The list L will now contain your results however many times you call it.

The problem you are facing is that once map has iterated once, it will yield nothing for each subsequent call. Hence you see an empty list for the second call.

For a more detailed explanation and advice on workarounds if you cannot exhaust your iterator but wish to use it twice, see Why can’t I iterate twice over the same data.

Answered By: jpp

Python 3.x returns a generator object:

$ python3 -c "print(map(lambda x: 2**x, range(7)))" 
<map object at 0x104203208>

You can extract those values using list(), but generators can be depleted. Hence subsequent use of list() will result in an empty [] since there are no more values to access with next() calls. I’d recommend experimenting with generators a little, or read a bit here https://wiki.python.org/moin/Generators. Hope this helps

Answered By: Dustc8ke