Course contentsShow
← Python
Lesson 273 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Flattening Nested Lists with Double Loops

You will be able to use multiple for-clauses within a single list comprehension to flatten nested structures into a flat list.

Flattening Nested Lists with Double Loops

In this lesson, you will learn how to use multiple for clauses within a single list comprehension to flatten nested lists into a single, clean sequence.

When you have a list that contains other lists (a "nested list"), a standard list comprehension often leaves you with the sub-lists still intact. For example, if you have data = [[1, 2], [3, 4]], a basic [item for item in data] simply returns the sub-lists [1, 2] and [3, 4].

To reach the individual numbers inside those sub-lists, we use a "double loop" inside the comprehension. Think of this as an instruction to Python: "For every sub-list in the main list, and then for every item in that sub-list, give me that item."

The Syntax

The syntax for this follows the same order as a standard nested for loop in regular code:

nested_list = [[1, 2], [3, 4], [5, 6]]

# The double loop comprehension
flat_list = [item for sublist in nested_list for item in sublist]

print(flat_list)
# Output: [1, 2, 3, 4, 5, 6]

Why the Order Matters

Notice the placement of the clauses. You start with the "outer" loop (for sublist in nested_list) and follow it immediately with the "inner" loop (for item in sublist). This tells Python to iterate through the main structure first, and for every piece it finds, drill down into it to extract the final elements.

While it might look a bit unusual at first, you can read it from left to right like a sentence: "Give me the item, for every sublist in the nested_list, and for every item in that sublist." This pattern is powerful because it allows you to transform, filter, and flatten complex, multi-layered data structures in one concise line of code, keeping your data pipelines clean and efficient.

Key Takeaway: By placing multiple for clauses in a list comprehension in the same order as a standard nested loop, you can condense nested data structures into a flat, one-dimensional list.