Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration count in python?

Tags:

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?

like image 758
Gadi A Avatar asked Dec 21 '11 13:12

Gadi A


People also ask

How do you count iterations in a for-loop?

Initialize a count variable and set it a number. Use a for loop to iterate over a sequence. On each iteration, reassign the count variable to its current value plus N.


1 Answers

Use enumerate.

for i, (a, b) in enumerate(l):
    # i will be the index of (a, b) in l
like image 68
hammar Avatar answered Sep 19 '22 22:09

hammar