Flattening Nested Iterables with Nested Comprehensions
In this lesson, you will learn how to transform multi-dimensional lists into a single, flat structure using the concise syntax of nested list comprehensions.
The Logic of the Flat Structure
When you have a list of lists, like matrix = [[1, 2], [3, 4]], you often need to extract every individual item into a single, one-dimensional list: [1, 2, 3, 4]. While you could write a standard for loop to append these items to a new list, Python allows you to perform this task in a single, readable line of code.
To flatten a list, you simply place your for clauses in the comprehension in the same order you would write them in a nested for loop.
Syntax in Action
Imagine you have a nested collection representing rows of data. Here is how you flatten it:
matrix = [[1, 2, 3], [4, 5], [6]]
# The nested comprehension approach
flat_list = [item for row in matrix for item in row]
print(flat_list)
# Output: [1, 2, 3, 4, 5, 6]
Understanding the Order
It is easy to get confused about the order of the loops. The rule of thumb is to read the comprehension from left to right, matching the structure of a standard nested loop:
for row in matrix: This is the "outer" loop that grabs each sub-list.for item in row: This is the "inner" loop that grabs the individual elements within that sub-list.item: This is the value that gets collected into your new list.
By placing the for clauses in this specific sequence, you are effectively telling Python to "go into the matrix, then go into each row, and pull out every item." This technique is not only idiomatic Python, but it is often faster than building a list manually through list.append() calls inside a traditional loop.
Key Takeaway: You can flatten a nested iterable by chaining for clauses in a list comprehension, following the exact same order you would use in a standard nested for loop.