I am trying to convert a map to list:
a=map(float, [1,2,3])
list(a) #first
list(a) #second
If I do list once(run to the row of #first), it returns [1,2,3] as I expect. However, if I do list twice, it returns []. I don't know what the problem is. Any comments are appreciated. Thanks.
CodePudding user response:
The whole reason to convert a map
to a list
is that a map is a single-use iterator; once you iterate over it once, it's exhausted ("empty") because it doesn't actually store its contents anywhere.
A list
stores all of its values and can be iterated over multiple times (it creates new iterators on demand).
The solution is to turn the map into a list once and save a reference to the list:
a=map(float, [1,2,3])
b = list(a)
# now you can iterate over b as much as you want
Note also that in place of map
you can simply do a list comprehension to create a list in a single step:
a = [float(i) for i in [1, 2, 3]]
# now you can iterate over a as much as you want