0

I'm a newbie and I'm trying to get my head around the enumerate function, and the behaviour of the enumerate object it generates.

Referencing the enumerate object seems to deplete it of its entries. Trying to interact with it in the same way twice in a row provides different results.

I've been thinking of it like a list, but this clearly isn't the way this kind of object behaves. Could somebody explain this spooky behaviour to me or direct me towards some resources that will?

MyList = ['one','two','three']
EnumList = enumerate(MyList,start=1)

print("Pass 1:")
print(EnumList)
for i in EnumList:
    print(i)
    
print("\nPass 2:")
print(EnumList)
for i in EnumList:
    print(i)
    
print("\nEnd")

Output:

Pass 1:
<enumerate object at 0x000001D79D0B4DB8>
(1, 'one')
(2, 'two')
(3, 'three')

Pass 2:
<enumerate object at 0x000001D79D0B4DB8>

End
Rockall
  • 21
  • 2
  • 1
    `enumerate()` returns a [Generator](https://wiki.python.org/moin/Generators) instead of a List :-) – BStadlbauer Oct 28 '20 at 17:17
  • 3
    If you want a list, you can always do `enum_list = list(enumerate(...))` (and same for all the other functions that return generators) – tobias_k Oct 28 '20 at 17:18
  • And you cannot rewind a Generator: https://stackoverflow.com/questions/1271320/resetting-generator-object-in-python#1271353 – gen_Eric Oct 28 '20 at 17:18
  • Thanks for the generator clues! @tobias_k , I had tried `list()` on it but I ended up getting the error message `'enumerate' object is not callable` – Rockall Oct 28 '20 at 17:27
  • 1
    @BStadlbauer it's not a generator, technically, but an iterator – juanpa.arrivillaga Oct 28 '20 at 17:29
  • @Rockall that's a *completely different error*, probably because you did `list = enumerate(whatever)` somewhere – juanpa.arrivillaga Oct 28 '20 at 17:30
  • @juanpa.arrivillaga Ahhh, thank you! Soon after starting I decided it was probably unwise to continue using 'list' as a variable name, but it appears it was still lingering in the iPython kernel. I've restarted the kernel and it's working perfectly now! – Rockall Oct 28 '20 at 17:40

1 Answers1

0

enumarate returns a generator instead of a list. Just use list(enumerate(data))

MyList = ['one','two','three']
EnumList = list(enumerate(MyList,start=1))

print("Pass 1:")
print(EnumList)
for i in EnumList:
    print(i)
    
print("\nPass 2:")
print(EnumList)
for i in EnumList:
    print(i)
    
print("\nEnd")
Mr. bug
  • 366
  • 2
  • 11