13

In C language we can use two index variable in a single for loop like below.

for (i = 0, j = 0; i < i_max && j < j_max; i++, j++)

Can some one tell how to do this in Python ?

3
  • Take a look here. Commented Aug 8, 2018 at 13:32
  • Yes, I got it. With zip we can do this. Commented Aug 8, 2018 at 13:36
  • 2
    Possible duplicate of "for loop" with two variables? Commented Aug 8, 2018 at 13:36

4 Answers 4

12

With zip we can achieve this.

>>> 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
Sign up to request clarification or add additional context in comments.

2 Comments

I would not agree. This does not account for different-sized lists, does it?
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.
1

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)

Comments

1

One possible way to do that is to iterate over a comprehensive list of lists. For example, if you want to obtain something like

for r in range(1, 3):
    for c in range(5, 7):
        print(r, c)

which produces

# 1 5
# 1 6
# 2 5
# 2 6

is by using

for i, j in [[_i, _j] for _i in range(1, 3) for _j in range(5, 7)]:
    print(i, j)

Maybe, sometimes one more line is not so bad.

Comments

0

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:

  • define the list of values for i and for j
  • build the iterable returning a pair of values from both lists: zip() is your friend in this case (if the lists have different sizes, it stops at the last element of the shortest one)
  • use the syntax 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

1 Comment

same answer as provided by @rashok

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.