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

4.7/5 - (3 votes)

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:

A Simple Introduction to List Comprehension in Python

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!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!