Ask Your Question
1

Does "map" destroy its input?

asked 9 years ago

Erel Segal-Halevi gravatar image

updated 8 years ago

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?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 9 years ago

updated 9 years ago

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

Preview: (hide)
link

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: 9 years ago

Seen: 346 times

Last updated: Feb 21 '16