13

Let's say I have a list of tuples l, and I do something like this:

for (a,b) in l:
     do something with a,b, and the index of (a,b) in l

Is there an easy way to get the index of (a,b)? I can use the index method of list, but what if (a,b) is not unique? I can also iterate on the indexes in the first place, but its cumbersome. Is there something simpler?

2 Answers 2

17

Use enumerate.

for i, (a, b) in enumerate(l):
    # i will be the index of (a, b) in l
Sign up to request clarification or add additional context in comments.

Comments

16

Use enumerate():

for i,(a,b) in enumerate(l):
   ... # `i` contains the index

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.