6 Ways to Flatten a List of Lists to a List in Python — CODEFATHER

Claudio Sabato
8 min readMay 17

Do you need to flatten a list of lists in Python? In this tutorial, we will examine techniques to flatten lists in Python.

Knowing how to flatten a list of lists into a single list is a common task. You can flatten a Python list using techniques such as list comprehension, the NumPy library, and for loops. The result of flattening a list of lists is a single list with no sublists.

Let’s learn how to flatten lists using Python!

What Does Flattening a Python List Mean?

Python, a robust and versatile programming language, offers programmers a number of approaches to common programming challenges.

In Python, “flattening” a list means transforming a multidimensional list or a list of lists into a one-dimensional list. It is the technique to simplify the list structure while maintaining the consistency and order of the data structure. In other words, the order of the elements in the flattened list of lists remains the same.

For example, let’s take an example of list of lists below:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The nested_list above contains three sub-lists (three lists inside the main list).

Flattening the list means converting the list of lists above into a one-dimensional list as shown below:

flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

So, what Python code do you have to write to accomplish this?

How Do You Flatten a List of Lists to a List in Python Using a Nested For Loop?

The for loop in Python flattens a list of lists by iterating over each sublist and then each item within those sublists. This basic approach, which takes advantage of Python’s built-in looping mechanism, converts a nested list structure into a flat list.

The following example shows how you can use a for loop to flatten a list of lists:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = []

for sublist in nested_list:
for item in sublist:
Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.