Course contentsShow
← Python
Lesson 119 of 1,0602. Control Flow and LogicFree lesson

Refactoring Nested Loops into Functional Expressions

Replace imperative nested loops with declarative list comprehensions to achieve more concise and readable data transformation logic.

Refactoring Nested Loops into Functional Expressions

In this lesson, you will learn how to replace multi-line, nested for loops with elegant, single-line list comprehensions to make your code more readable and expressive.

The Problem with Nesting

When we use nested loops—placing a loop inside another loop—we are performing a series of steps to build a new list. While this works, it often creates a "pyramid of code" that can be hard to follow. Take this example, where we want to combine every letter from one list with every number from another:

letters = ['a', 'b']
numbers = [1, 2]
combined = []

for letter in letters:
    for number in numbers:
        combined.append((letter, number))

The logic is correct, but it takes four lines just to build a simple list. As your logic grows, these nested blocks become clutter.

The Functional Approach

List comprehensions allow us to shift from imperative programming (telling the computer how to loop and append) to declarative programming (describing what the resulting data should look like).

In a list comprehension, you can represent a nested loop by simply placing the outer loop first and the inner loop immediately after it. Here is the same logic as above, refactored:

combined = [(letter, number) for letter in letters for number in numbers]

Why This Works

The list comprehension reads almost like an English sentence: "Create a list of tuples (letter, number) for every letter in letters, and for every number in numbers."

By collapsing these two loops, you reduce the visual noise. You no longer need to initialize an empty list, manage loop headers, or call the .append() method. The transformation happens all in one place, which helps keep your code clean and Pythonic.

Whenever you find yourself writing a basic nested loop to filter or map items into a new list, ask yourself if a single list comprehension could do the job more clearly.

Key Takeaway: You can replace nested for loops with list comprehensions by placing the nested iteration logic inside a single pair of brackets, resulting in more concise and readable code.