Python double for loop one line | Example code

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:

Python double for loop one line

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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.