Last modified: Jan 26, 2026 By Alexander Williams
Python Nested List Comprehension Guide
List comprehensions are a powerful Python feature. They let you create lists in a single, readable line. Nested list comprehensions extend this power. They work with lists inside lists.
This guide explains nested list comprehensions. You will learn the syntax and see practical examples. We will also cover common use cases and best practices.
What is a Nested List Comprehension?
A nested list comprehension has multiple for loops. It processes multi-dimensional data structures. Think of it as a loop inside another loop, but written in a compact form.
The basic syntax is: [expression for item1 in iterable1 for item2 in iterable2]. The order of loops matters. It reads from left to right, just like nested for loops.
They are ideal for transforming nested lists. You can filter, map, and flatten data efficiently. This keeps your code clean and Pythonic.
Basic Syntax and Structure
Let's break down the syntax. The outer loop comes first. The inner loop comes next. The expression at the beginning defines the final output.
# Basic nested list comprehension structure
# [output_expression for outer_item in outer_list for inner_item in outer_item]
# Example: Create a matrix (list of lists)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Goal: Get all elements as a single list
flattened = [num for row in matrix for num in row]
print(flattened)
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The code loops through each row in the matrix. Then, it loops through each num in that row. It collects every num into a new list.
This is more concise than using nested for loops with append. For more on appending to nested lists, see our guide on Python List in List Append.
Practical Examples
Let's explore more examples. These show the real power of nested comprehensions.
Example 1: Creating a Multiplication Table
# Generate a 3x3 multiplication table
table = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print("Multiplication Table:")
for row in table:
print(row)
Output:
Multiplication Table:
[1, 2, 3]
[2, 4, 6]
[3, 6, 9]
Here, the outer comprehension creates each row. The inner comprehension calculates the products. The result is a list of lists, perfect for representing tabular data.
Example 2: Filtering Nested Data
You can add conditional logic. Use if statements to filter data.
# A list of student grades per class
grades = [[88, 92, 75], [95, 60, 82], [70, 85, 90]]
# Find all high grades (>= 85) from all classes
high_grades = [grade for class_grades in grades for grade in class_grades if grade >= 85]
print("High grades:", high_grades)
Output: High grades: [88, 92, 95, 85, 90]
The if grade >= 85 part filters each number. Only high grades are included in the final list. This is a clean way to extract specific data from complex structures.
Example 3: Flattening a List of Lists
Flattening is a common task. It converts a 2D list into a 1D list.
nested_list = [['a', 'b'], ['c', 'd', 'e'], ['f']]
flat_list = [item for sublist in nested_list for item in sublist]
print("Flattened list:", flat_list)
Output: Flattened list: ['a', 'b', 'c', 'd', 'e', 'f']
This pattern is very useful. Once flattened, you can easily perform operations like finding the maximum in a Python list or calculating a Python list summation.
Nested Comprehensions with Conditionals
Conditionals can be placed in two spots. They can filter the inner loop or the outer loop. Placement changes the result.
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Conditional on INNER loop (filters items within each sublist)
inner_filter = [num for row in data for num in row if num % 2 == 0]
print("Inner filter (even numbers):", inner_filter)
# Conditional on OUTER loop (filters which sublists to process)
outer_filter = [num for row in data if sum(row) > 10 for num in row]
print("Outer filter (rows sum > 10):", outer_filter)
Output:
Inner filter (even numbers): [2, 4, 6, 8]
Outer filter (rows sum > 10): [4, 5, 6, 7, 8, 9]
The first example only processes even numbers from all rows. The second example only processes rows where the sum is greater than 10, then takes all numbers from those rows.
When to Use Nested List Comprehensions
Use them for simple transformations and flattening. They make code shorter and often faster.
Avoid them when logic becomes complex. If you need multiple conditions or complex calculations, a traditional for loop is clearer. Readability is key.
They are perfect for data preparation. For instance, after processing data with a comprehension, you might need to export a Python list of lists to CSV.
Common Pitfalls and Best Practices
Beginners often make a few mistakes. Here is how to avoid them.
1. Incorrect Loop Order: The loops run in the order they are written. The first for is the outermost loop.
2. Overly Complex Comprehensions: If it doesn't fit on one line or is hard to read, use a for loop instead.
3. Forgetting the Output Expression: The expression at the start defines what is collected. It can be the item itself, a function of the item, or a constant.
Always test with simple data first. Then, apply it to your real dataset.
Conclusion
Nested list comprehensions are a concise Python tool. They help you process multi-dimensional lists efficiently. You learned the syntax, saw practical examples, and understood best practices.
Start with simple flattening tasks. Gradually try adding filters. Remember to prioritize code clarity. When a comprehension gets messy, a traditional loop is a better choice.
Mastering this concept will make your data processing code more elegant and efficient. Keep practicing with different datasets to become proficient.