How to Flatten a List of Lists in Python

Avatar

By squashlabs, Last Updated: Oct. 15, 2023

How to Flatten a List of Lists in Python

Flattening a list of lists is a common operation in Python, and there are several ways to achieve this. In this answer, we will explore two popular methods: using nested list comprehensions and using the itertools.chain.from_iterable() function.

Method 1: Nested List Comprehensions

One way to flatten a list of lists in Python is by using nested list comprehensions. This method is concise and efficient, making it a popular choice among Python developers.

Here's an example of how to use nested list comprehensions to flatten a list of lists:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)

Output:

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

In the example above, we have a nested list nested_list containing three sublists. The nested list comprehension item for sublist in nested_list for item in sublist iterates over each sublist in nested_list and then iterates over each item in the sublist, effectively flattening the list.

Related Article: How to Uninstall All Pip Packages in Python

Method 2: itertools.chain.from_iterable()

Another way to flatten a list of lists in Python is by using the itertools.chain.from_iterable() function from the itertools module. This method is more explicit and readable, especially for larger and more complex lists.

Here's an example of how to use itertools.chain.from_iterable() to flatten a list of lists:

import itertools

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = list(itertools.chain.from_iterable(nested_list))
print(flattened_list)

Output:

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

In the example above, we import the itertools module and then use the chain.from_iterable() function to flatten the nested_list. The function chain.from_iterable() takes the nested list as an argument and returns an iterator that produces the flattened list. We convert the iterator to a list using the list() function for easier printing and manipulation.

Best Practices

Related Article: How to Use Switch Statements in Python

When flattening a list of lists in Python, consider the following best practices:

1. Use nested list comprehensions for simple and concise code. This method is ideal for small to medium-sized lists.

2. Use itertools.chain.from_iterable() for larger or more complex lists. This method is more explicit and allows for easier customization or modification.

3. If you only need to iterate over the flattened list and don't need a new list object, consider using a generator expression instead of a list comprehension. This can save memory and improve performance, especially for large lists.

4. If you need to flatten a list of lists to a specific depth, consider using a recursive function or a third-party library like flatten-list.

More Articles from the Python Tutorial: From Basics to Advanced Concepts series:

How To Get Substrings In Python: Python Substring Tutorial

Learn how to extract substrings from strings in Python with step-by-step instructions. This tutorial covers various methods, including string slicing… read more

How to End Python Programs

This guide provides software developers with essential information on correctly terminating Python programs. It covers various methods for ending Pyt… read more

Structuring Data for Time Series Analysis with Python

Structuring data for time series analysis in Python is essential for accurate and meaningful insights. This article provides a concise guide on the c… read more

Converting cURL Commands to Python

This technical guide provides an overview of converting cURL commands into Python, offering step-by-step instructions on using the requests module an… read more

How to Use Hash Map In Python

Hash maps are a powerful tool for data storage and retrieval in Python. This concise guide will walk you through the process of using hash maps in Py… read more

How to Convert Bytes to a String in Python 3

Step-by-step guide on converting bytes to a string in Python 3. Method 1: Using the decode() method, Method 2: Using the str() constructor, Best Prac… read more

Tutorial on Python Generators and the Yield Keyword

Python generators and the yield keyword are powerful tools for creating and memory-friendly code. This detailed guide explores their implementation, … read more

How to Execute a Program or System Command in Python

This guide provides simple steps to execute system commands or programs in Python. Learn how to use the subprocess.run() function and subprocess.Pope… read more

Python Typing Module Tutorial: Use Cases and Code Snippets

Learn how to use the Python Typing Module for type hints and annotations in your code. This tutorial covers installation and setup, various annotatio… read more

Flask-Babel For Internationalization & Localization

Flask-Babel simplifies internationalization and localization in Flask, enabling developers to handle multi-language data and encoding with ease. This… read more