logo

Writing Multiple for Loops in One Line Using Python 📂Programing

Writing Multiple for Loops in One Line Using Python

Code

To repeat for index i up to 2 and j up to 4, you can write the for loop as follows:

>>> for i in range(3):
...     for j in range(5):
...             if j == 4:
...                     print((i,j))
...             else :
...                     print((i,j), end="")
...
(0, 0)(0, 1)(0, 2)(0, 3)(0, 4)
(1, 0)(1, 1)(1, 2)(1, 3)(1, 4)
(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)

Using the product() from the standard library itertools, you can handle the same for loop operation in one line.

>>> for i, j in itertools.product(range(3), range(5)):
...     if j == 4:
...             print((i,j))
...     else :
...             print((i,j), end="")
...
(0, 0)(0, 1)(0, 2)(0, 3)(0, 4)
(1, 0)(1, 1)(1, 2)(1, 3)(1, 4)
(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)

When used with zip(), you can implement the following loop.

>>> for i,(j,k) in zip(range(3**2), itertools.product(range(3), range(3))):
...     print(i,j,k)
...
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2

Environment

  • OS: Windows10
  • Version: Python 3.9.2