So I have a for loop.
>>> row = [5, 2, 5, 4, 2, 2, 5, 5, 5, 2]
>>> for i in row:
if i == 5:
print(row.index(i))
if i == 2:
print(row.index(i))
OUTPUT
0
1
0
1
1
0
0
0
1
I want to get: 0 1 2 4 5 6 7 8 9.
In other words, I want to get the index of the i I'm currently looking at in the for loop, if it is = 5 or 2... any easy way to do this?
Use the enumerate() function to produce a running index:
for index, i in enumerate(row):
if i == 5:
print(index)
if i == 2:
print(index)
or simpler still:
for index, i in enumerate(row):
if i in (2, 5):
print(index)
For completeness sake, an alternative if one didn't want to use enumerate for some reason:
row = [5, 2, 5, 4, 2, 2, 5, 5, 5, 2]
indices = filter(lambda idx: row[idx] in (5,2), xrange(len(row)))
# [0, 1, 2, 4, 5, 6, 7, 8, 9]
Or as a list-comp:
indices = [idx for idx in xrange(len(row)) if row[idx] in (5, 2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With