Alternative to 'for i in xrange(len(x))'

Alam picture Alam · Feb 23, 2009 · Viewed 7k times · Source

So I see in another post the following "bad" snippet, but the only alternatives I have seen involve patching Python.

for i in xrange(len(something)):
  workwith = something[i]
  # do things with workwith...

What do I do to avoid this "antipattern"?

Answer

Greg Hewgill picture Greg Hewgill · Feb 23, 2009

If you need to know the index in the loop body:

for index, workwith in enumerate(something):
    print "element", index, "is", workwith