10

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 ?

rashok
  • 12,790
  • 16
  • 88
  • 100

4 Answers4

8

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
rashok
  • 12,790
  • 16
  • 88
  • 100
  • I would not agree. This does not account for different-sized lists, does it? – sdgaw erzswer Aug 08 '18 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 08 '18 at 13:40
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)
sdgaw erzswer
  • 2,182
  • 2
  • 26
  • 45
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.

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
Laurent H.
  • 6,316
  • 1
  • 18
  • 40