Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexing current value in for loop? Python

Tags:

python

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?

like image 304
Rimoun Avatar asked Dec 12 '25 11:12

Rimoun


2 Answers

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)
like image 143
Martijn Pieters Avatar answered Dec 17 '25 00:12

Martijn Pieters


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)]
like image 30
Jon Clements Avatar answered Dec 16 '25 23:12

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!