Flatten A List of Lists in Python
Last Updated :
06 Feb, 2024
Flattening a list of lists is a common task in Python, often encountered when dealing with nested data structures. Here, we’ll explore some widely-used methods to flatten a list of lists, employing both simple and effective techniques.
How To Flatten A List Of Lists In Python?
Below, are the methods for How To Flatten A List Of Lists In Python.
Using Nested Loops
In this example, below code initializes a nested list and flattens it using nested loops, iterating through each sublist and item to create a flattened list. The result is then printed using print("Flattened List:", flattened_list)
.
Python3
nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
flattened_list = []
for sublist in nested_list:
for item in sublist:
flattened_list.append(item)
print ( "Flattened List:" , flattened_list)
|
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using List Comprehension
In this example, below code starts with a nested list and uses list comprehension to flatten it into a single list. The result, a flattened list, is displayed using `print(“Flattened List:”, flattened_list)`.
Python3
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:" , flattened_list)
|
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using itertools.chain()
The itertools.chain()
function is another efficient method for flattening. The chain()
function takes multiple iterables and flattens them into a single iterable.
Python3
from itertools import chain
nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
flattened_list = list (chain( * nested_list))
print ( "Flattened List:" , flattened_list)
|
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using functools.reduce()
Using functools.reduce()
with the operator concat
function is another option. reduce()
applies concat
successively to the elements of the list, achieving flattening.
Python3
from functools import reduce
from operator import concat
nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
flattened_list = reduce (concat, nested_list)
print ( "Flattened List:" , list (flattened_list))
|
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Please Login to comment...