Flatten nested lists with a list comprehension

This post is part of the programming series.

Here’s my programming tip of the day. You can flatten a nested list of lists into a single flat list with a nested list comprehension. Wow, phrasing.

It’s easy to get confused. If you forget how to do it, you can first write out the whole loop:

# Flatten list
>>> flat = []
>>> nested = [ [1, 2, 3], [4, 5, 6] ]
>>> for sub in nested:
>>>    for element in sub:
>>>        flat.append(element)
>>> flat
[1, 2, 3, 4, 5, 6]

To collapse this into a one-liner, work from the outer scope inwards:

flat = [ el for sub in nested for el in sub ]

Voila. Lean and mean.

Version control on notebooks using pre-commit and Jupytext <-- Latest

Zip is its own inverse <-- Next

Wrong feature preprocessing is a source of train-test leakage <-- Previous

Morton's Perverse Holism - A Twelve-step program <-- Random


Do you want to link a webmention to this page?
Provide the URL of your response for it to show up here.


Nothing yet. Be the first!