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

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.

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 the for loop to flatten a list of lists, the sum() function is straightforward and more readable as it’s a Python one-liner:

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

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

You can also achieve this with a list comprehension:

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.