3

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?

0

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ding ding ding, we have a winner in the 33rd second :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.