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]



Previous Article
Next Article

Similar Reads

Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print (
5 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() + extend() The combination of a
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its value in dictionary. Input : test_list = ["Gfg", "
4 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Practice Tags :