Enumerate object is destroyed by casting?

N

Nick Jacobson

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'}
{}
 
J

Jeffrey Froman

Nick said:
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
 
S

Shalabh Chaturvedi

Nick said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top