Flatten a nested list of arbitrary depth in python


There are many situations where a flat or one-dimensional list is preferable to an nested list. Counting, filtering of elements is one example. Another important use-case for flattened lists, when list hierarchy is irrelevant, is to use conventional functions which require a flat list as argument. Pythonian tuple unpacking, i.e. arg = (1,2,3); func(*arg)  too is often a convenient option to have.

source/copyright: realitypod.com


Following are several exemplary methods of flattening lists in Python.



Loading ....
Note: For exhaustive handling of iterables, import the itertools module (Python > 2.2).
LihatTutupKomentar