Ask Your Question
1

Does "map" destroy its input?

asked 2016-02-21 09:09:15 -0500

Erel Segal-Halevi gravatar image

updated 2016-06-06 14:45:44 -0500

FrédéricC gravatar image

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 flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
2

answered 2016-02-21 10:28:48 -0500

updated 2016-02-21 10:28:58 -0500

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

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-02-21 09:09:15 -0500

Seen: 30 times

Last updated: Feb 21 '16