In this lesson, you will learn how to build multi-dimensional arrays or matrix structures using nested list comprehensions to keep your code concise and readable.
When you need to create a matrix—like a grid of numbers—you could write a standard for loop to append rows to a list. However, nested list comprehensions allow you to define this structure in a single, declarative line. The secret is to think of the comprehension as a "loop within a loop."
The "Loop-in-a-Loop" Structure
When nesting, the leftmost for clause acts as the outer loop (creating the rows), and the inner for clause acts as the inner loop (filling each row).
Imagine you want to create a 3x3 matrix filled with zeros. A traditional approach requires creating an empty list and running two nested for loops. With a nested comprehension, you simply write:
# Creating a 3x3 matrix of zeros
matrix = [[0 for column in range(3)] for row in range(3)]
print(matrix)
# Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Why it Matters
The power of this syntax becomes clear when you perform operations during creation. For example, if you want to generate a multiplication table where each cell contains the product of its coordinates, you can replace the 0 with the math logic:
# A 3x3 multiplication table (1-indexed)
table = [[(r + 1) * (c + 1) for c in range(3)] for r in range(3)]
print(table)
# Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Keeping Code Readable
While nesting is powerful, remember that readability is paramount. If your nested comprehension becomes more than two levels deep, it often becomes difficult for others (or your future self) to decipher. In such cases, breaking the logic out into standard loops is a better architectural choice for long-term maintainability.
Always define your outer loop first, then follow with the inner logic inside the brackets to define the structure of your nested data.
Key Takeaway: Nested list comprehensions act as a shorthand for nested loops, allowing you to generate multi-dimensional data structures efficiently by nesting the "inner" loop expression inside the "outer" loop construct.