December 10, 2017
Flatten a list of lists in Python
Welcome to a new Python code snippet. In this post, we are going to suggest a couple of methods to flatten a list of lists. The final output is going to be a one dimensional list. Let us take an example:
1 2 3 4 |
# Given the following list of lists # Write code to flatten it. The output # should be [1, 2, 3, 'A', 'B', 'C'] A = [[1, 2, 3], ['A', 'B', 'C']] |
- Using nested loops
1 2 3 4 5 |
B = [] for x in A: for y in x: B.append(y) print(B) |
- Using list comprehensions
1 2 |
B = [y for x in A for y in x] print(B) |
- Using sum function
1 2 |
B = sum(A, []) print(B) |
- Using list extend
1 2 3 4 |
B = [] for x in A: B.extend(x) print(B) |
- Using chain from itertools
1 2 3 |
from itertools import chain B = list(chain(*A)) print(B) |
- Using chain.from_iterable
1 2 |
B = list(chain.from_iterable(A)) print(B) |
- Using reduce, lambda
1 2 3 |
from functools import reduce B = reduce(lambda x,y: x+y, A) print(B) |
- Using reduce, add operator
1 2 3 4 |
from functools import reduce from operator import add B = reduce(add, A) print(B) |
That is all. Thanks for visiting, for questions and feedback, please use the comments section below.