views:

425

answers:

5

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

+19  A: 

See Pythonic

for workwith in something:
    # do things with workwith
kmkaplan
+1: 80% of the time, this is what you meant.
S.Lott
fine, unless you want to modify the value. consider for workwith in something: workwith += 1
vartec
@vartec: that’s true, but given Alam question he does not.
kmkaplan
+2  A: 

for example:

[workwith(i) for i in something]
SilentGhost
'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
and? <!-- -->
SilentGhost
A: 

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

for i in x: workwith = i

will work fine.

Xolve
SilentGhost's answer is better :-)
Xolve
+19  A: 

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

for index, workwith in enumerate(something):
    print "element", index, "is", workwith
Greg Hewgill
+1: 20% of the time, this is what you meant.
S.Lott
+5  A: 

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 :)

myroslav
+1: No, your answer is most appropriate, and the most complete, actually.
ΤΖΩΤΖΙΟΥ