Question
I have a Python list containing other lists:
nested = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
How can I flatten this structure so the result becomes:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to combine the inner lists into a single flat list.
Notes:
- This question is about flattening one level of nesting.
- If the data comes from a nested list comprehension, it may be better to rewrite the comprehension directly.
- If the structure is nested to arbitrary depth, a recursive approach is a different problem.
Short Answer
By the end of this page, you will understand what it means to flatten a list of lists in Python, when to use each common approach, and how to write clear, correct code using loops, list comprehensions, and standard library tools.
Concept
Flattening a list of lists means turning a structure like this:
[[1, 2], [3, 4], [5]]
into this:
[1, 2, 3, 4, 5]
The key idea is that you have an outer list containing multiple inner lists, and you want to collect all items from the inner lists into one new list.
This matters because nested data appears everywhere in programming:
- rows returned from data processing
- grouped API results
- chunks of parsed text
- batches of records
- matrix-like data structures
In Python, flattening one level is common and straightforward. The most beginner-friendly and widely used options are:
- a nested list comprehension
- a regular
forloop withappend()orextend() itertools.chain.from_iterable()
A very important detail: flattening one level is not the same as flattening arbitrarily deep nesting.
For example:
Mental Model
Think of a list of lists like a stack of trays in a cafeteria.
- The outer list is the stack of trays.
- Each inner list is one tray holding items.
- Flattening means taking all items off each tray and putting them onto one long table.
So this:
[[1, 2, 3], [4, 5], [6]]
is like:
- tray 1:
1, 2, 3 - tray 2:
4, 5 - tray 3:
6
After flattening, all items are on one table:
[1, 2, 3, 4, 5, 6]
You are not changing the items themselves. You are just removing one layer of grouping.
Syntax and Examples
Common ways to flatten one level
1. List comprehension
This is the most common Pythonic solution:
nested = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
flat = [item for sublist in nested for item in sublist]
print(flat)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation:
for sublist in nestedloops over each inner listfor item in sublistloops over each value inside that inner list- each
itemis collected into the new list
2. Using a regular loop with extend()
Step by Step Execution
Consider this example:
nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
Let us trace it.
Step 1: Start with the outer list
nested = [[1, 2], [3, 4], [5]]
The outer list has three inner lists:
[1, 2][3, 4][5]
Step 2: First loop picks a sublist
for sublist in nested
First, sublist becomes:
[1, 2]
Step 3: Second loop picks items from that sublist
Real World Use Cases
Flattening one level of nesting is useful in many real programs.
Combining batched API results
An API may return data in pages:
pages = [
["user1", "user2"],
["user3"],
["user4", "user5"]
]
Flattening gives one list of users.
Merging rows extracted from files
Suppose you parse several CSV files and each file produces a list of records. Flattening combines all records into one list for further processing.
Joining search results
A search system may collect results from multiple sources:
results_by_source = [
["result_a", "result_b"],
["result_c"],
[]
]
Flattening creates one result stream.
Processing tokenized text
If each sentence is converted into a list of words, flattening can produce one long list of words for counting or analysis.
Working with chunked data
Data is often processed in chunks for performance. After processing, flattening can recombine those chunks into one list.
Real Codebase Usage
In real Python codebases, developers usually choose the flattening style that best matches readability and context.
Common patterns
List comprehension for simple cases
Used when the data is clearly a list of iterables and the transformation is short.
flat_ids = [user_id for group in grouped_ids for user_id in group]
extend() inside loops
Useful when building the result gradually or mixing flattening with validation.
flat = []
for batch in batches:
if not batch:
continue
flat.extend(batch)
This pattern often appears with guard clauses like if not batch: continue.
Validation before flattening
In production code, data may not always be shaped as expected.
flat = []
for sublist in nested:
if not isinstance(sublist, list):
raise TypeError("Expected a list of lists")
flat.extend(sublist)
Common Mistakes
1. Using append() instead of extend()
Broken code:
nested = [[1, 2], [3, 4]]
flat = []
for sublist in nested:
flat.append(sublist)
print(flat)
Output:
[[1, 2], [3, 4]]
Why it happens:
append()adds the whole sublist as one element
Fix:
for sublist in nested:
flat.extend(sublist)
2. Getting list comprehension order wrong
Broken code:
nested = [[1, 2], [3, 4]]
flat = [sublist for item in sublist for sublist in nested]
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
| List comprehension | [item for sublist in nested for item in sublist] | Short, readable flattening | Very common and idiomatic |
for loop + extend() | flat.extend(sublist) | Beginners, extra logic, validation | Easy to debug |
itertools.chain.from_iterable() | list(chain.from_iterable(nested)) | Iteration-heavy code, large data | Can be used lazily |
sum(nested, []) | sum(nested, []) |
Cheat Sheet
Flatten one level in Python
Best common solution
flat = [item for sublist in nested for item in sublist]
Clear loop version
flat = []
for sublist in nested:
flat.extend(sublist)
Standard library version
from itertools import chain
flat = list(chain.from_iterable(nested))
Important rule
These flatten only one level.
[[1, 2], [3, [4, 5]]]
becomes:
[1, 2, 3, [4, 5]]
Remember
append(sublist)keeps nesting
FAQ
How do I flatten a list of lists in Python?
Use a list comprehension:
flat = [item for sublist in nested for item in sublist]
What is the easiest way to flatten a nested list in Python?
For one level of nesting, a list comprehension or a loop with extend() is easiest.
What is the difference between append() and extend() in Python?
append()adds one object as a single elementextend()adds each item from an iterable
For flattening, extend() is usually the correct choice.
Does this flatten deeply nested lists too?
No. These common solutions flatten only one level.
Is itertools.chain.from_iterable() better than a list comprehension?
It depends. A list comprehension is often easier to read. chain.from_iterable() is great when you want iterator-based processing.
Why is sum(nested, []) discouraged for flattening?
Mini Project
Description
Build a small Python utility that combines multiple batches of order IDs into one flat list. This mirrors a real-world case where data arrives in grouped chunks, such as paginated API responses or batch processing jobs.
Goal
Create a function that takes a list of lists of order IDs and returns one flat list in the same order.
Requirements
- Write a function named
flatten_orders. - The function must accept a list of lists.
- Return a single flat list containing all values in order.
- Ignore empty inner lists without causing errors.
- Demonstrate the function with sample input and print the result.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.