Python when evaluating loop conditions
2 answers
Your code will work, but using a loop counter is often not considered very "pythonic". Usage for
works just as well and eliminates the counter:
>>> foo = [0, 1, 2]
>>> for bar in foo:
if bar % 2: # append to foo for every odd number
foo.append(len(foo))
print bar
0
1
2
3
4
If you need to know how far the list is, you can use enumerate
:
>>> foo = ["wibble", "wobble", "wubble"]
>>> for i, bar in enumerate(foo):
if i % 2: # append to foo for every odd number
foo.append("appended")
print bar
wibble
wobble
wubble
appended
appended
+3
a source to share