How to flatten list of lists in python

Python List

In this post, we are going to learn different Ways to How to flatten list of lists in python with a code example. It includes a list of lists, a list of tuples.

  • List Compreshension to flatten list of lists
  • Python Flatten list Recursively
  • lambda to flatten irregular List of Lists
  • Python Flatten A list of tuples
  • Python Flatten nested lists
  • Flatten list Python Numpy
  • Sum() function to Flatten List of Lists
  • Flatten list of strings Python
  • module to Flatten list of lists

What is flat a list in Python


The list object is a data structure in Python. The list of lists is known as a 2D array because it contains a 2-dimensional representation of data. Whenever in python we convert a 2D array to a 1D array, it is called flattening.

If you would like to understand this with the example then please check the below sample of lists. Original list is list of lists , means it contains a list which have nested lists in it. What we want to achieve is the converted flatten list which is single list that have all the elements of original list , but they all are arranged as elements of a single list, not nested lists.

Original List

#Original List of lists

[[6, 28, 89, 45], [15, 16, 17], [1, 2, 3], [56, 65]]

Converted Flatten List

#Converted Flatten List

[6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

1.List comprehensions to Flatten list of lists


In this example we are using list comprehension to flat a nested list

Python Program Example

list_of_list = [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3],[56,65]]

flatten_list = [ele for sublist in list_of_list for ele in sublist]

print('Original list = \n ', list_of_list)

print('\n converted list= \n', flatten_list)

Output

Original list = 
  [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3], [56, 65]]

converted list= 
 [6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

2.Python Flatten list Recursively


In this example we have define a function flatten_list(list_of_list) that takes nested list as an argument and flatten it recursively.

Python Program Example

def flatten_list(list_of_list):

    if len(list_of_list) == 1:

        if type(list_of_list[0]) == list:

                result_list = flatten_list(list_of_list[0])

              else:                
                    result_list = list_of_list

              elif type(list_of_list[0]) == list:

        result_list = flatten_list(list_of_list[0]) + flatten_list(list_of_list[1:])

        else:        
            result_list = [list_of_list[0]] + flatten_list(list_of_list[1:])

        return result_list

list_of_list = [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3],[56,65]]


print('flatten list = \n',flatten_list(list_of_list))

Output

flatten list = 
 [6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

3.lambda to Flatten irregular List of Lists


In this example we are using lambda to flatten list of lists.Let understand with below example.

list_of_lists = [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3],56,65]

list_flatten = lambda list_of_lists:[ele for item in list_of_lists for ele in list_flatten(item)] if type(list_of_lists) is list else [list_of_lists]

print('original list = \n',list_of_lists) 
print('flatten list = \n',list_flatten(list_of_lists))

Output

original list = 
 [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3], 56, 65]
flatten list = 
 [6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

4.Flatten A list of tuples Python


In this code example we are flattening the list of tuples and by using list comprehension we are converting it into flatten list.

list_of_tuples = [(6, 28, 89, 45), (15, 16, 17), (10,11,45,35),(56,65)]

flatten_list = [ele for subl in list_of_tuples for ele in subl]

print('original list = \n ',list_of_tuples)
print('Transformed list = \n',flatten_list)

Output

original list = 
  [(6, 28, 89, 45), (15, 16, 17), (10, 11, 45, 35), (56, 65)]
Transformed list = 
 [6, 28, 89, 45, 15, 16, 17, 10, 11, 45, 35, 56, 65]

5. Python Flatten nested lists


To achieve flattening of a nested list, we can use deep flattening. Let us understand with an example of how to achieve this.

Python Program to flatten nested lists

from iteration_utilities import deepflatten
nested_deep_lists = [[6, 28, 89, 45], [15, 16, 17], [[1,[3,[4,[9,[10]]]]]],[56,65]]

flatten_list = list(deepflatten(nested_deep_lists))


print('Transformed list = \n',flatten_list)

Output

Transformed list = 
 [6, 28, 89, 45, 15, 16, 17, 1, 3, 4, 9, 10, 56, 65]

6. Flatten list Python Numpy


In this Example we are using Python numpy module concatenate() method that takes lists of list as an agrument and use flat property to flat the list.

Python Program Example

import numpy 
list_of_lists = [[6, 28, 89, 45], [15, 16, 17], [10,11,45,35],[56,65]]


flatten_list = list(numpy.concatenate(list_of_lists).flat)


print('flatten list = \n ', flatten_list)

Output


flatten list = 
  [6, 28, 89, 45, 15, 16, 17, 10, 11, 45, 35, 56, 65]

7.Sum() function to Flatten List of Lists


In this example we are Using sum() function to flatten a list of list.Let us understand with below example

list_of_lists = [[6, 28, 89, 45], [15, 16, 17], [10,11,45,35],[56,65]]

flatten_list = sum(list_of_lists, [])

print('flatten list = \n ', flatten_list)

Output

flatten list = 
  [6, 28, 89, 45, 15, 16, 17, 10, 11, 45, 35, 56, 65]

8.Flatten list of strings Python


In this example we have a list of string we have defined a method that called recursively to flatten a list.

Python Program list of strings


def flatten_lstStr(list_of_lists):
    res_List = []
    for item in list_of_lists:
        if isinstance(item,list):
            res_List.extend(flatten_lstStr(item))
        else: res_List.append(item)
    return res_List

list_of_str = ['Students', ['Name', 'Max'], ['Subject', ['math','XI', '100']]]



print(flatten_lstStr(list_of_str))

Output

['Students', 'Name', 'Max', 'Subject', 'math', 'XI', '100']

9.Functools module to Flatten list of lists


There are two ways to use functools module to flatten a list

  • reduce-add
  • reduce-iconcat
import operator
from functools import reduce
 
list_of_lists = [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3],[56,65]]
flatten_list = reduce(operator.add, list_of_lists)


print('flatten list = \n',flatten_list)

Output

flatten list = 
 [6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

Flatten list of lists Using Functools (reduce-iconcat)

import operator
from functools import reduce
 
list_of_lists = [[6, 28, 89, 45], [15, 16, 17], [1, 2, 3],[56,65]]
flatten_list = reduce(operator.iconcat, list_of_lists, [])

print('flatten list = \n',flatten_list)

Output


flatten list = 
 [6, 28, 89, 45, 15, 16, 17, 1, 2, 3, 56, 65]

Conclusion

We have explored different Methods to flatten the list of lists in Python3 with code examples. Now by using the above methods we can easily flat a list of lists in Python.