How to flatten list in Python?


In Python, a list of lists (or cascaded lists) resembles a two-dimensional array - although Python doesn't have a concept of the array as in C or Java. Hence, flattening such a list of lists means getting elements of sublists into a one-dimensional array-like list. For example, a list [[1,2,3],[4,5,6]] is flattened into [1,2,3,4,5,6].

This can be achieved by different techniques, each one of them is explained below:

Flatten List using Nested for Loop

Using the nested for loop to append each element of sublist in a flat list

Example:
nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
flatlist=[]
for sublist in nestedlist:
    for element in sublist:
        flatlist.append(element)
print(flatlist)
Output
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]

Flatten List using List Comprehension

List comprehension technique gives the same result in a single compact statement.

Example:
nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
flatlist=[element for sublist in nestedlist for element in sublist]
print(flatlist)
Output
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]

Flatten List using the reduce() Function of functools Module

The first argument to the reduce() function is a function itself with two arguments, and the second argument is a list. Argument function is applied cumulatively to elements in the list. For example, reduce(lambda a,b:a+b, [1,2,3,4,5]) returns cumulative sum of numbers in the list.

Example:
from functools import reduce
flatlist = reduce(lambda a,b:a+b, nestedlist)
print(flatlist)
Output
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]

Recall that the + symbol is defined as a concatenation operator for sequence data types (list, tuple, and string). Instead of a lambda function, we can also use the concat() function defined in the operator module as an argument to cumulatively append the sublists to flatten.

Example:
from functools import reduce
from operator import concat

nestedlist = [ [1, 2, 3, 4], ["Ten", "Twenty", "Thirty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
flatlist = reduce(concat, nestedlist)
print(flatlist)
Output
[1, 2, 3, 4, 'Ten', 'Twenty', 'Thirty', 1.1, 10.0, (1+2j), 20.55, 3.142]