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
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
...