# Does "map" destroy its input? I write the following in the SageMath cloud:

Bob="xyz"
sB = subsets(Bob)
print map(str, sB)
print map(str, sB)


and the output is:

['[]', "['x']", "['y']", "['x', 'y']", "['z']", "['x', 'z']", "['y', 'z']", "['x', 'y', 'z']"]
[]


I.e, after the first "map", the variable "sB" becomes empty!

Why does this happen?

edit retag close merge delete

Sort by » oldest newest most voted sage: Bob="xyz"
sage: sB = subsets(Bob)
sage: sB
<generator object powerset at 0x18fe82f00>


At this point, sB is a generator, and after you've done map(str,sB), the generator has been exhausted, so doing map(str,sB) a second time does nothing: there are no elements left in sB to apply map to. You could instead do

sage: sB = list(subsets(Bob))


Now sB is a list which can be accessed over and over again.

sage: print map(str, sB)
['[]', "['x']", "['y']", "['x', 'y']", "['z']", "['x', 'z']", "['y', 'z']", "['x', 'y', 'z']"]
sage: print map(str, sB)
['[]', "['x']", "['y']", "['x', 'y']", "['z']", "['x', 'z']", "['y', 'z']", "['x', 'y', 'z']"]


(See http://stackoverflow.com/questions/12... for a related question.)

more