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?
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.
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 ”.
Using enumerate() is more beautiful but not faster for looping over a collection and indices.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With