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.



On circular imports in Python <-- Latest

Zip is its own inverse <-- Next

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

Building a Note-taking System with Vanilla Vim <-- Random

Webmentions


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

Comments

Nothing yet. Be the first!