How to use 2 index variable in a single for loop in python
Clash Royale CLAN TAG#URR8PPP
How to use 2 index variable in a single for loop in python
In C
language we can use two index variable in a single for
loop like below.
C
for
for (i = 0, j = 0; i < i_max && j < j_max; i++, j++)
Can some one tell how to do this in Python
?
Python
for (i=0, j=0, ...)
Yes.Typo mistake.
– rashok
Aug 8 at 13:32
Take a look here.
– Vasilis G.
Aug 8 at 13:32
Yes, I got it. With zip we can do this.
– rashok
Aug 8 at 13:36
Possible duplicate of "for loop" with two variables?
– MooingRawr
Aug 8 at 13:36
3 Answers
3
With zip
we can achieve this.
zip
>>> i_max = 5
>>> j_max = 7
>>> for i, j in zip(range(0, i_max), range(0, j_max)):
... print str(i) + ", " + str(j)
...
0, 0
1, 1
2, 2
3, 3
4, 4
I would not agree. This does not account for different-sized lists, does it?
– sdgaw erzswer
Aug 8 at 13:39
Good solution by @rashok . Works well for equal sized list. If you wanted a dataframe, you could create a tuple of (i, j) and append to a list. That list can be used to create a dataframe.
– Sagar Dawda
Aug 8 at 13:40
If the first answer does not suffice; to account for lists of different sizes, a possible option would be:
a = list(range(5))
b = list(range(15))
for i,j in zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))):
print(i,j)
Or if one wants to cycle around shorter list:
from itertools import cycle
for i,j in zip(range(5),cycle(range(2)):
print(i,j)
You can do this in Python by using the syntax for i,j in iterable:
. Of course in this case the iterable must return a pair of values. So for your example, you have to:
for i,j in iterable:
i
j
zip()
for i,j in iterable:
Here is an example:
i_max = 7
j_max = 9
i_values = range(i_max)
j_values = range(j_max)
for i,j in zip(i_values,j_values):
print(i,j)
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
# 6 6
same answer as provided by @rashok
– Sagar Dawda
Aug 8 at 13:46
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You probably mean
for (i=0, j=0, ...)
?– cheersmate
Aug 8 at 13:30