Use List Comprehension way to write a double for loop one line in Python. With this method, you can iterate over two or more iterables that are nested into each other.
Syntax
[operation for i in iterable1 for j in iterable2]
Example double for loop one line in Python
Simple example code.
Nested List Comprehension
num = [1, 2, 3]
alph = ['A', 'B']
[print(x, y) for x in num for y in alph]
Output:
Or use For Loop with List Comprehension
num = [1, 2, 3]
alph = ['A', 'B']
for x in num: [print(x, y) for y in alph]
Another example
Use Python exec() function use one-liner string using the newline character '\n'
.
exec("for x in iter1:\n for y in iter2:\n print(x, y)")
Do comment if you have any doubts and suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.