9

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"?

Community
  • 1
  • 1

5 Answers5

23

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

for index, workwith in enumerate(something):
    print "element", index, "is", workwith
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
22

See Pythonic

for workwith in something:
    # do things with workwith
kmkaplan
  • 18,655
  • 4
  • 51
  • 65
12

As there are two answers to question that are perfectly valid (with an assumption each) and author of the question didn't inform us about the destiny of index, the valid answer should read:

If you do not need index at all:

for workwith in something:
    print "element", workwith

If you need index:

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

If my answer is not appropriate, comment please, and I'll delete it :)

Community
  • 1
  • 1
myroslav
  • 3,703
  • 23
  • 29
0

for example:

[workwith(i) for i in something]
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 'something' is a collection of objects. From the original, it does not appear that 'something' is necessarily integers nor that 'workwith' is a collection at all. 'workwith' appears to be a temporary variable for workign with 'something'. – hughdbrown Feb 23 '09 at 19:01
-3

What is x? If its a sequence or iterator or string then

for i in x:
    workwith = i

will work fine.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Xolve
  • 22,298
  • 21
  • 77
  • 125
  • SilentGhost's answer is better :-) – Xolve Feb 23 '09 at 18:15
  • I can't think of any situation in which this is the best answer. It appears to be an inferior version of kmkaplan's answer. (I realize it was posted before kmkaplan, but it *is* possible to delete one's answer, once an unambiguously superior one has been proposed.) Nevertheless, I didn't put -1 on it, since it has been knocked down enough by others. – ToolmakerSteve Mar 01 '14 at 04:03