
Situation
I solved the task of flattening a pandas dataframe containing list elements into a list using list comprehension. However, this abuses list comprehension and results in code that is much less readable.
[passage for lst_passage in make_passages['passages'] for passage in lst_passage]
Solutions
- Use itertools
import itertools
passages = list(itertools.chain.from_iterable(make_passages['passages']))
- Unpacking (using *)
passages = list(*passage for passage in make_passages['passages'])
- Functions
def flatten_list(nested_list):
return [item for sublist in nested_list for item in sublist]
passages = flatten_list(make_passages['passages'])