Ask Your Question
1

Does "map" destroy its input?

asked 2016-02-21 16:09:15 +0200

Erel Segal-Halevi gravatar image

updated 2016-06-06 21:45:44 +0200

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 17:28:48 +0200

updated 2016-02-21 17:28:58 +0200

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 16:09:15 +0200

Seen: 237 times

Last updated: Feb 21 '16