In this short guide, we will learn how to write nested for loops in a single line using Python list comprehensions. This technique makes code more concise, readable, and Pythonic for creating lists from nested iterations.

Here you can find the short answer:

(1) Basic nested loop comprehension

result = [x * y for x in range(3) for y in range(3)]

(2) Nested loop with condition

result = [x * y for x in range(5) for y in range(5) if x != y]

(3) Creating 2D matrix

matrix = [[x + y for y in range(3)] for x in range(3)]

1. Basic Nested Loop to List Comprehension

Convert a double nested loop that creates coordinate pairs:

coordinates = [(x, y) for x in ['Apple', 'Google', 'Microsoft'] 
               for y in ['2024', '2025']]

print(f"Total combinations: {len(coordinates)}")
for coord in coordinates:
    print(coord)

Output Result:

Total combinations: 6
('Apple', '2024')
('Apple', '2025')
('Google', '2024')
('Google', '2025')
('Microsoft', '2024')
('Microsoft', '2025')

Equivalent traditional code:

for x in ['Apple', 'Google', 'Microsoft']:
    for y in ['2024', '2025']:
        coordinates.append((x, y))

2. Nested Loop with Conditional Filtering

Create product combinations excluding same-item pairs:

products = ['iPhone', 'iPad', 'MacBook']

combos = [(p1, p2) for p1 in products for p2 in products if p1 != p2]

print(f"Product pairs: {len(combos)}")
for combo in combos:
    print(f"{combo[0]} + {combo[1]}")

Output Result:

Product pairs: 6
iPhone + iPad
iPhone + MacBook
iPad + iPhone
iPad + MacBook
MacBook + iPhone
MacBook + iPad

Real-world use: Generating product bundles, user recommendations, A/B test combinations.

3. Creating Multiplication Table (2D Matrix)

Build a multiplication table using nested comprehensions:

table = [[x * y for y in range(1, 6)] for x in range(1, 6)]

print("5x5 Multiplication Table:")
for row in table:
    print(row)

Output Result:

5x5 Multiplication Table:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[5, 10, 15, 20, 25]

Common use: Creating distance matrices, price tables, coordinate grids.

4. Flattening Nested Lists

Flatten a list of lists into a single list:

departments = [
    ['John', 'Sarah', 'Mike'],
    ['Emma', 'David'],
    ['Lisa', 'Tom', 'Anna', 'Chris']
]

all_employees = [name for dept in departments for name in dept]

print(f"Total employees: {len(all_employees)}")
print(all_employees)

Output Result:

Total employees: 8
['John', 'Sarah', 'Mike', 'Emma', 'David', 'Lisa', 'Tom', 'Anna', 'Chris']

Practical use: Combining multi-department data, merging categories, aggregating results.

Order Matters: Left to Right

Critical rule: In list comprehensions, for loops read left to right, same order as traditional nested loops:

[(x, y) for x in [1, 2] for y in ['a', 'b']]

Is equivalent to:

for x in [1, 2]:
    for y in ['a', 'b']:
        result.append((x, y))