Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map in Python 3 vs Python 2 [duplicate]

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?

like image 954
Septacle Avatar asked Jun 03 '18 22:06

Septacle


1 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.

like image 168
jpp Avatar answered Oct 16 '22 23:10

jpp