2

On converting enumerate object becomes empty:

myTuple = (1, 2, 3)

myEnum = enumerate(myTuple)

print(myEnum)
print(list(myEnum))

print(myEnum)
print(list(myEnum))
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 2
    `enumerate` returns an object that you can iterate once. That uses it up. It does not "become null". – khelwood Nov 05 '20 at 13:28
  • 1
    Does this answer your question? [Why can't I iterate twice over the same data?](https://stackoverflow.com/questions/25336726/why-cant-i-iterate-twice-over-the-same-data) – Tomerikoo Nov 05 '20 at 13:54
  • In Python speak, an instance of `enumerate` is an *iterator*. By contrast, a tuple is not an iterator itself, but is an example of an *iterable*; you can call `iter(myTuple)` to get a new iterator over the tuple, which like all iterators can only be iterated over once. Most things that expect an iterator (like `list`) will try to call `iter` on its argument to get an iterator, so that you don't often need to think about the difference between the two. – chepner Nov 05 '20 at 14:13

1 Answers1

2

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108