0
0
PythonHow-ToBeginner · 3 min read

How to Flatten a List in One Line in Python

You can flatten a nested list in one line using a list comprehension like [item for sublist in nested_list for item in sublist]. Alternatively, use list(itertools.chain.from_iterable(nested_list)) for a clean approach.
📐

Syntax

The common syntax to flatten a list of lists in one line uses list comprehension:

  • [item for sublist in nested_list for item in sublist]: loops through each sublist, then each item inside it, collecting all items into a single flat list.
  • Alternatively, list(itertools.chain.from_iterable(nested_list)) uses the chain function to flatten.
python
[item for sublist in nested_list for item in sublist]
💻

Example

This example shows how to flatten a nested list of numbers into a single list using list comprehension.

python
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
Output
[1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

One common mistake is trying to flatten a list with more than two levels of nesting using this one-liner, which only works for one level of nested lists.

Also, using sum(nested_list, []) to flatten is less efficient and not recommended.

python
nested_list = [[1, 2], [3, 4], [5, 6]]
# Wrong: sum method (less efficient)
flat_list_wrong = sum(nested_list, [])
print(flat_list_wrong)

# Right: list comprehension
flat_list_right = [item for sublist in nested_list for item in sublist]
print(flat_list_right)
Output
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
📊

Quick Reference

Use list comprehension for simple one-level nested lists. For deeper or unknown nesting, consider recursive methods or libraries.

  • One-level flatten: [item for sublist in nested_list for item in sublist]
  • Using itertools: list(itertools.chain.from_iterable(nested_list))
  • Avoid: sum(nested_list, []) due to inefficiency

Key Takeaways

Use list comprehension to flatten one-level nested lists in one line.
itertools.chain.from_iterable is a clean alternative for flattening.
Avoid using sum(nested_list, []) as it is inefficient.
This method works only for one level of nesting, not deeper nested lists.
For complex nesting, consider recursive flattening methods.