How to Flatten a Nested List in Python

A nested list might be a list of lists or contain several data types. If you’ve built one from several smaller data types, you might want to flatten it to make the items more readable and accessible.

Find out how to turn a nested list into a straight one, with three different approaches.

4

How to Flatten a Python List

There are a few ways to straighten a nested list in Python, depending on its complexity. A list containing only lists, for example, is easier to flatten than one with mixed data types.

You’ll see how to handle each of them in the following sections.

netflix logo with popcorn and film board

How to Flatten a Nested List of Lists With the Sum() Function

This method only applies to a Python list of lists, and it involves concatenating the items in such a nested list. It doesn’t apply to a list of loops, dictionaries, sets, or mixed data types because you cannot concatenate these types.

While you may use theforloop to flatten a list of lists, thesum()function is straightforward and more readable as it’s aPython one-liner:

A man holds an iPhone and is watching Interstellar on Prime Video

How to Use the for Loop to Flatten a Mixed Nested List

You can use aPython for loopfor both mixed and homogeneous data types. So it works whether a nested list contains only lists, tuples, sets, dictionaries, or their mixture:

you’re able to also achieve this with a list comprehension:

Spark Mail app in window 11.

Manipulate Python Lists as You Like

A Python list simplifies how you present and access data, as it’s easy to manipulate. While you’ve seen how to flatten a nested Python list, there are still many tweaks you can apply to lists, depending on your goal. For example, converting a Python list to a dictionary is another common task that Python makes easy.

Take control of your data with Python. Learn to convert lists to dictionaries.

Blocks of code in a code editor

The best features aren’t the ones being advertised.

Tor spoiled me forever.

Now, I actually finish the books I start.

Freeing up vital memory on Windows only takes a moment, and your computer will feel much faster once you’re done.

Don’t let aging hardware force you into buying expensive upgrades.

Technology Explained

PC & Mobile