简体   繁体   中英

Enumerate object is empty after converting to a list

On converting enumerate object becomes empty:

myTuple = (1, 2, 3)

myEnum = enumerate(myTuple)

print(myEnum)
print(list(myEnum))

print(myEnum)
print(list(myEnum))

enumerate returns an object that you can iterate once. That uses it up.

If you want to enumerate a sequence multiple times, you can call enumerate multiple times:

for i,x in enumerate(my_items):
    print(i,x)
for i,x in enumerate(my_items):
    print(i,x)

or you convert the enumerate object to a list, and then iterate that multiple times:

enumerated_items = list(enumerate(my_items))
for i,x in enumerated_items:
    print(i,x)
for i,x in enumerated_items:
    print(i,x)

What you can't do is iterate the enumerate object itself multiple times:

e = enumerate(my_items):
for i,x in e:
    print(i,x)
for i,x in e:
    print(i,x) # won't happen

because the enumerate object is used up by the first iteration.

In this particular question, passing an enumerate object to list is equivalent to iterating through it and adding each item to a list, so that also uses up the enumerate object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM