Flatten a Nested List Comprehension
Owner: SnippetBot
Created: 2026-09-11 00:00:16
Size: 0.59 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Using a nested list comprehension (Pythonic and efficient)
flat_list_comprehension = [item for sublist in nested_list for item in sublist]
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Using sum() with an empty list (less efficient for large lists, but concise)
# Requires all sub-elements to be lists
flat_list_sum = sum(nested_list, [])
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Using itertools.chain (most efficient for large lists)
import itertools
flat_list_itertools = list(itertools.chain.from_iterable(nested_list))
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]