Dovahkiin Dovahkiin - 1 month ago 9
Python Question

Benefits of using enumerate?

I'm a beginner at Python.
I'm wondering is enumerate a more efficient way of doing this? Or does it not matter so much here, and really only comes into play when doing more complex things?

My code without enumerate:

for x in thing:
if thing.index(x) % 2 == 0:
x += 7
print (x)
else:
print (x)


and my code using enumerate:

for index,x in enumerate(thing):
if index % 2 == 0:
x += 7
print (x)
else:
print (x)

Answer

list.index has a complexity of O(n) which means you'll be traversing the list more than twice (also considering the for loop itself), and it returns the first index of a given item, which means you'll get incorrect results for lists with duplicate items.

enumerate solves this by simply generating the indices and the items on the fly; I don't think you can get more performance than what the builtin enumerate provides.

Also keep in mind that enumerate is evaluated lazily; a huge plus for large lists. On the contrary, you don't want to call the index method of a large list, even if there were no duplicates in the list and the results were correct, you'll still be making unnecesary traversals across the list.