Blog of me. I’m Alexander Jones.

24 February 2010

Python tip: enumerate(list) vs. xrange(len(list))

For a long time, when wanting a counting variable with which to index some list in a Python loop, I've used for i in xrange(len(some_list)). However, I've since discovered the built-in enumerate function, so you can instead do for i, item in enumerate(some_list). This has the benefit of already giving you effectively item = some_list[i] for each iteration of the loop, and also working on iterators that don't necessarily have a length. (enumerate simply gives you an iterator that returns each item of the input collection back together with a counting number. Far too simple!)

Hopefully this will help someone, but if not, it’ll remind me later!