This post will discuss how to flatten a nested list in Python.
For instance, [[[1, 2, 3], [4, 5]], [6, 7, 8]] should be converted into [1, 2, 3, 4, 5, 6, 7, 8].
1. Using iteration_utilities package
The deepflatten[] function of the iteration_utilities package can be used to flatten an iterable. It can be installed with pip pip install iteration_utilities.
1 2 3 4 5 6 | from iteration_utilities import deepflatten lists = [[[1, 2, 3], [4, 5]], [6, 7, 8]] joinedlist = list[deepflatten[lists]] print[joinedlist]# prints [1, 2, 3, 4, 5, 6, 7, 8] |
2. Generator using recursion
You can use a generator using recursion using the yield from expression [introduced in Python 3.3] for generator delegation. Heres a working example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def flatten[L]: for l in L: if isinstance[l, list]: yield from flatten[l] else: yield l if __name__ == '__main__': lists = [[[1, 2, 3], [4, 5]], [6, 7, 8]] joinedlist = list[flatten[lists]] print[joinedlist]# prints [1, 2, 3, 4, 5, 6, 7, 8] |
DownloadRun Code
Thats all about flattening a nested list in Python.
Related Post:
Flatten a list of lists in Python