Open In App

Flatten A List of Lists in Python

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Sample List of Lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten using Nested Loops
flattened_list = []
for sublist in nested_list:
    for item in sublist:
        flattened_list.append(item)
 
# Display the result
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




# Sample List of Lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten using List Comprehension
flattened_list = [item for sublist in nested_list for item in sublist]
 
# Display the result
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
 
# Sample List of Lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten using itertools.chain()
flattened_list = list(chain(*nested_list))
 
# Display the result
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
 
# Sample List of Lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten using functools.reduce() and operator.concat
flattened_list = reduce(concat, nested_list)
 
# Display the result
print("Flattened List:", list(flattened_list))


Output

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads