How to Write a Nested For Loop in One Line Python?

Summary: To write a nested for loop in a single line of Python code, use the one-liner code [print(x, y) for x in iter1 for y in iter2] that iterates over all values x in the first iterable and all values y in the second iterable.

Problem: How to write a nested for loop as a Python one-liner? Roughly speaking, you want to iterate over two or more iterables that are nested into each other. Here’s an example of a multi-liner with two nested loops:

iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']

for x in iter1:
    for y in iter2:
        print(x, y)

'''
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
'''

How to accomplish this in a single line?

Let’s dive into multiple methods! Here’s a quick overview:

Exercise: Instead of printing the outputs, store them in three lists of tuples. Print the lists after creating them so that your output has three lines!

Method 1: Nested List Comprehension

Write a Nested For Loop in One Line Python

The first method makes use of the powerful feature of list comprehension:

# Method 1: Nested List Comprehension
[print(x, y) for x in iter1 for y in iter2]

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

Here’s a short video tutorial on list comprehension in case you need a quick refresher:

Method 2: exec()

You can always one-linerize any multi-liner by using Python’s built-in exec(...) function.

# Method 2: exec()
exec("for x in iter1:\n    for y in iter2:\n        print(x, y)")

You wrote the multi-liner as a one-liner string using the newline character '\n'. Note that you must ensure that the three lines are properly indented.

Method 3: For Loop with List Comprehension

Again, you use list comprehension—but now only for the inner loop.

# Method 3: For Loop with List Comprehension
for x in iter1: [print(x, y) for y in iter2]

Note that many coders would consider this to be “unpythonic” because you create a list consisting only of None values—the return values from the print() function calls.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!