Only index needed: enumerate or (x)range?

LarsVegas picture LarsVegas · Aug 10, 2012 · Viewed 11.7k times · Source

If I want to use only the index within a loop, should I better use the range/xrange function in combination with len()

a = [1,2,3]
for i in xrange(len(a)):
    print i 

or enumerate? Even if I won't use p at all?

for i,p in enumerate(a):
    print i    

Answer

Jon Clements picture Jon Clements · Aug 10, 2012

I would use enumerate as it's more generic - eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn't that big a deal - while xrange(len(something)) although (to me) more easily readable as your intent - will break on objects with no support for len...