Question

How to Flatten a List of Lists in Python

pythonlistmultidimensional-arrayflatten

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 for loop with append() or extend()
  • itertools.chain.from_iterable()

A very important detail: flattening one level is not the same as flattening arbitrarily deep nesting.

For example:

[[1, 2], [3, [4, 5]]]

A one-level flatten produces:

[1, 2, 3, [4, 5]]

It does not recursively flatten [4, 5] unless you use a different recursive solution.

Also, flattening usually creates a new list rather than modifying the original nested structure in place.

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.

Take Quiz

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 nested loops over each inner list
  • for item in sublist loops over each value inside that inner list
  • each item is collected into the new list

2. Using a regular loop with extend()

nested = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
flat = []

for sublist in nested:
    flat.extend(sublist)

print(flat)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

  • extend() adds all elements from an iterable to the list
  • this is different from append(), which would add the whole sublist as one element

3. Using itertools.chain.from_iterable()

from itertools import chain

nested = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
flat = list(chain.from_iterable(nested))
print(flat)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

  • chain.from_iterable(nested) produces items from each inner list in order
  • wrapping it with list() converts the result into a real list

append() vs extend()

flat = []
flat.append([1, 2])
print(flat)

Output:

[[1, 2]]

Now compare:

flat = []
flat.extend([1, 2])
print(flat)

Output:

[1, 2]

Use extend() when flattening because you want the contents of each sublist, not the sublist itself.

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

for item in sublist

From [1, 2], the items are:

  • 1
  • 2

These are added to the result list.

Current result:

[1, 2]

Step 4: Move to the next sublist

Now sublist becomes:

[3, 4]

The inner loop adds:

  • 3
  • 4

Current result:

[1, 2, 3, 4]

Step 5: Final sublist

Now sublist becomes:

[5]

The inner loop adds:

  • 5

Final result:

[1, 2, 3, 4, 5]

Equivalent expanded form

The comprehension:

flat = [item for sublist in nested for item in sublist]

is equivalent to:

flat = []
for sublist in nested:
    for item in sublist:
        flat.append(item)

This expanded version is often easier for beginners to read first.

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.

Take Quiz

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)

Lazy processing with chain

If the next step can consume an iterator, developers may avoid building a list immediately.

from itertools import chain

all_items = chain.from_iterable(nested)
for item in all_items:
    process(item)

This is useful when handling large datasets.

Flattening after grouping or mapping

A common workflow is:

  • group data
  • transform each group into a list
  • flatten the results

For example:

groups = [[1, 2], [3], [4, 5]]
squared = [[n * n for n in group] for group in groups]
flat = [n for group in squared for n in group]

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]

Why it fails:

  • the loop order is backward
  • sublist is used before it is defined

Correct version:

flat = [item for sublist in nested for item in sublist]

3. Assuming it works for deeply nested data

Code:

nested = [[1, 2], [3, [4, 5]]]
flat = [item for sublist in nested for item in sublist]
print(flat)

Output:

[1, 2, 3, [4, 5]]

Why this matters:

  • this only removes one layer of nesting
  • it does not recursively flatten deeper structures

4. Using sum() to flatten lists

You may see this:

nested = [[1, 2], [3, 4]]
flat = sum(nested, [])

This works for small examples, but it is usually discouraged.

Why avoid it:

  • it is less clear
  • it is inefficient for larger lists because repeated list addition creates extra work

5. Forgetting that strings are iterable

If your data contains strings instead of lists, extend() will add each character:

flat = []
flat.extend("abc")
print(flat)

Output:

['a', 'b', 'c']

If that is not what you want, validate your input first.

Comparisons

ApproachExampleBest forNotes
List comprehension[item for sublist in nested for item in sublist]Short, readable flatteningVery common and idiomatic
for loop + extend()flat.extend(sublist)Beginners, extra logic, validationEasy to debug
itertools.chain.from_iterable()list(chain.from_iterable(nested))Iteration-heavy code, large dataCan be used lazily
sum(nested, [])sum(nested, [])Almost never recommendedWorks, but inefficient

append() vs extend()

MethodWhat it doesExample result
append(x)Adds x as one element[].append([1, 2]) gives [[1, 2]]
extend(x)Adds each item from x[].extend([1, 2]) gives [1, 2]

List comprehension vs chain

FeatureList comprehensionchain.from_iterable()
Easy for beginnersYesModerate
Reads like plain PythonYesYes, once familiar
Produces list directlyYesNo, use list(...) if needed
Can stay lazyNoYes
Good for quick scriptsYesYes
Take Quiz

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
  • extend(sublist) removes one level of nesting
  • avoid sum(nested, []) for flattening large lists

Pattern to memorize

[item for sublist in nested for item in sublist]

Read it as:

  • for each sublist in nested
  • for each item in sublist
  • collect item

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 element
  • extend() 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?

Because it is less efficient and less clear than other options.

Can I flatten tuples or other iterables the same way?

Yes, as long as the outer container holds inner iterables. But be careful with strings, because they flatten into characters.

Take Quiz

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

  1. Write a function named flatten_orders.
  2. The function must accept a list of lists.
  3. Return a single flat list containing all values in order.
  4. Ignore empty inner lists without causing errors.
  5. Demonstrate the function with sample input and print the result.
Take Quiz

Keep learning

Related questions

View more