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.



Regular expressions with optional starting or ending groups <-- Latest

Zip is its own inverse <-- Next

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

Object Orientation: Strategy Pattern <-- 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!



Leave a comment

Thank you

Your post has been submitted and will be published once it has been approved.

OK

Something went wrong!

Your comment has not been submitted. Return to the page by clicking OK.

OK