Skip to content

Commit ed4a560

Browse files
authored
Merge pull request #393 from realpython/python-flatten-list
Sample code for the article on flattening list
2 parents fe09cae + 61d9d71 commit ed4a560

File tree

4 files changed

+90
-0
lines changed

4 files changed

+90
-0
lines changed

python-flatten-list/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Flatten a List of Lists in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [How to Flatten a List of Lists in Python](https://realpython.com/python-flatten-list/).

python-flatten-list/flatten.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from functools import reduce
2+
from itertools import chain
3+
from operator import add, concat, iconcat
4+
5+
6+
def flatten_extend(matrix):
7+
flat_list = []
8+
for row in matrix:
9+
flat_list.extend(row)
10+
return flat_list
11+
12+
13+
def flatten_concatenation(matrix):
14+
flat_list = []
15+
for row in matrix:
16+
flat_list += row
17+
return flat_list
18+
19+
20+
def flatten_comprehension(matrix):
21+
return [item for row in matrix for item in row]
22+
23+
24+
def flatten_chain(matrix):
25+
return list(chain.from_iterable(matrix))
26+
27+
28+
def flatten_reduce_lambda(matrix):
29+
return list(reduce(lambda x, y: x + y, matrix, []))
30+
31+
32+
def flatten_reduce_add(matrix):
33+
return reduce(add, matrix, [])
34+
35+
36+
def flatten_reduce_concat(matrix):
37+
return reduce(concat, matrix, [])
38+
39+
40+
def flatten_reduce_iconcat(matrix):
41+
return reduce(iconcat, matrix, [])
42+
43+
44+
def flatten_sum(matrix):
45+
return sum(matrix, [])
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import numpy as np
2+
3+
matrix = np.array(
4+
[
5+
[9, 3, 8, 3],
6+
[4, 5, 2, 8],
7+
[6, 4, 3, 1],
8+
[1, 0, 4, 5],
9+
]
10+
)
11+
12+
matrix.flatten()

python-flatten-list/performance.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from timeit import timeit
2+
3+
import flatten # noqa
4+
5+
SIZE = 1000
6+
TO_MS = 1000
7+
NUM = 10
8+
FUNCTIONS = [
9+
"flatten_extend",
10+
"flatten_concatenation",
11+
"flatten_comprehension",
12+
"flatten_chain",
13+
"flatten_reduce_lambda",
14+
"flatten_reduce_add",
15+
"flatten_reduce_concat",
16+
"flatten_reduce_iconcat",
17+
"flatten_sum",
18+
]
19+
20+
matrix = [list(range(SIZE))] * SIZE
21+
22+
results = {
23+
func: timeit(f"flatten.{func}(matrix)", globals=globals(), number=NUM)
24+
for func in FUNCTIONS
25+
}
26+
27+
print(f"Time to flatten a {SIZE}x{SIZE} matrix (in milliseconds):\n")
28+
29+
for func, time in sorted(results.items(), key=lambda result: result[1]):
30+
print(f"{func + '()':.<30}{time * TO_MS / NUM:.>7.2f} ms")

0 commit comments

Comments
 (0)