By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,938 Members | 1,579 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,938 IT Pros & Developers. It's quick & easy.

Enumerate object is destroyed by casting?

P: n/a
Casting an 'enumerate' object destroys it?? Is that supposed to
happen, or is it a bug?
For example:
a = ['a', 'b', 'c']
e = enumerate(a)
print dict(e)
print dict(e)
Result:
{0: 'a', 1: 'b', 2: 'c'}
{}
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Nick Jacobson wrote:
Casting an 'enumerate' object destroys it??**Is*that*supposed*to
happen, or is it a bug?
For example:
a = ['a', 'b', 'c']
e = enumerate(a)
print dict(e)
print dict(e)
Result:
{0: 'a', 1: 'b', 2: 'c'}
{}


This is supposed to happen. Enumerate objects are essentially generators --
casting the object doesn't "destroy" it; but iterating over its values
"uses them up". In other words, after the first dict() call, your
enumerator is now empty. The same thing would happen if you simply iterated
over the object, like:

for thing in e:
print thing
Jul 18 '05 #2

P: n/a
Nick Jacobson wrote:
Casting an 'enumerate' object destroys it?? Is that supposed to
happen, or is it a bug?
For example:
a = ['a', 'b', 'c']
e = enumerate(a)
print dict(e)
print dict(e)
Result:
{0: 'a', 1: 'b', 2: 'c'}
{}


This is not casting (there is no casting in Python). It is creating a
new dict from an iterable. enumerate(a) creates an iterable that runs
over the items *once*. After that there is nothing left to return.

HTH,

Shalabh

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.