Skip to content

Commit f629131

Browse files
committed
Sample code for the article on flattening list
1 parent ac82180 commit f629131

13 files changed

+101
-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/).
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
def flatten_comprehension(matrix):
2+
return [item for row in matrix for item in row]
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def flatten_concatenation(matrix):
2+
flat = []
3+
for row in matrix:
4+
flat += row
5+
return flat
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def flatten_extend(matrix):
2+
flat = []
3+
for row in matrix:
4+
flat.extend(row)
5+
return flat
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from itertools import chain
2+
3+
4+
def flatten_itertools_chain(matrix):
5+
return list(chain.from_iterable(matrix))
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import numpy as np
2+
3+
matrix = [list(range(100))] * 4
4+
arr = np.array(matrix)
5+
6+
7+
def flatten_numpy_flatten(matrix):
8+
return matrix.flatten()
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import pandas as pd
2+
3+
matrix = [list(range(100))] * 4
4+
df = pd.DataFrame(matrix)
5+
6+
7+
def flatten_pandas(matrix):
8+
return pd.DataFrame(matrix.to_numpy().flatten())
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from functools import reduce
2+
from operator import add
3+
4+
5+
def flatten_reduce_add(matrix):
6+
return reduce(add, matrix, [])
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from functools import reduce
2+
from operator import concat
3+
4+
5+
def flatten_reduce_concat(matrix):
6+
return reduce(concat, matrix, [])
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from functools import reduce
2+
from operator import iconcat
3+
4+
5+
def flatten_reduce_iconcat(matrix):
6+
return reduce(iconcat, matrix, [])

0 commit comments

Comments
 (0)