Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple counters in a single for loop : Python

Tags:

Is it possible in Python to run multiple counters in a single for loop as in C/C++?

I would want something like -- for i,j in x,range(0,len(x)): I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop?

like image 662
Sayan Ghosh Avatar asked Apr 20 '10 06:04

Sayan Ghosh


People also ask

Can you have multiple counters in Python?

When you're counting the occurrences of a single object, you can use a single counter. However, when you need to count several different objects, you have to create as many counters as unique objects you have. To count several different objects at once, you can use a Python dictionary.

How do you increment a counter in a for loop in Python?

Increment variable in loop python In python, to increment a variable value in a loop, we can use the while loop directly for increasing or decreasing the iteration value. After writing the above code (increment variable in loop python), Ones you will print “my_list[i]” then the output will appear as an “ 11 13 15 ”.

Is enumerate faster than for loop?

Using enumerate() is more beautiful but not faster for looping over a collection and indices.


2 Answers

You want zip in general, which combines two iterators, as @S.Mark says. But in this case enumerate does exactly what you need, which means you don't have to use range directly:

for j, i in enumerate(x): 

Note that this gives the index of x first, so I've reversed j, i.

like image 85
Andrew Jaffe Avatar answered Sep 26 '22 08:09

Andrew Jaffe


You might want to use zip

for i,j in zip(x,range(0,len(x))): 

Example,

>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> print zipped [(1, 4), (2, 5), (3, 6)] >>> for a,b in zipped: ...     print a,b ... 1 4 2 5 3 6 >>> 

Note: The correct answer for this question is enumerate as other mentioned, zip is general option to have multiple items in a single loop

like image 38
YOU Avatar answered Sep 23 '22 08:09

YOU