“Flatten a list of lists” in Python means the process of converting a nested list structure into a single, one-dimensional list. In other words, it involves taking a list that contains other lists as elements and creating a new list that contains all the individual elements from the nested lists in a linear sequence.
For example, given the following list of lists:
original_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
The goal of flattening this list is to obtain a new list like this:
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
This process can be useful in various situations where you want to work with a single flat list of elements rather than a nested structure. Python provides several methods to achieve this.
Flatten list of lists Python example
To flatten a list of lists in Python, you can use various methods. Here are a few common approaches:
1. Using a nested list comprehension:
original_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = [item for sublist in original_list for item in sublist]
print(flattened_list)
2. Using the itertools.chain.from_iterable()
method:
from itertools import chain
original_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = list(chain.from_iterable(original_list))
print(flattened_list)
3. Using the sum()
function with a start value of an empty list:
original_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = sum(original_list, [])
print(flattened_list)
Output:
Choose the method that you find most readable and suitable for your use case. The first two methods use a list comprehension or the chain.from_iterable()
method, which are generally considered more Pythonic and efficient. The third method using sum()
may not be as efficient for larger lists due to the overhead of concatenating lists.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.