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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With