TIL about Python’s “enumerate”

I’ve been writing Python for more than 10 years, and I can’t count the number of times I’ve written code like this:

index = 0
for thing in array:
    do_something_with(index, thing) # Because I care about the index AND the item
    index += 1

But today I learned about the built-in enumerate function which does exactly the same thing, but avoids any chance of getting “index” and “thing” out of sync (not that I’ve ever made that mistake, of course…).

I’m not going to rewrite any old code for fear of adding new bugs, but I’ll remember to enumerate going forward.

Thanks, Dr. Drang!