Gadi A
Gadi A

Reputation: 3539

Iteration count in python?

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?

Upvotes: 13

Views: 6835

Answers (2)

hammar
hammar

Reputation: 139840

Use enumerate.

for i, (a, b) in enumerate(l):
    # i will be the index of (a, b) in l

Upvotes: 17

NPE
NPE

Reputation: 500317

Use enumerate():

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

Upvotes: 16

Related Questions