This post will discuss how to flatten a list of lists in Python.

For instance, [[1, 2, 3], [4, 5], [6, 7, 8]] should be converted into list [1, 2, 3, 4, 5, 6, 7, 8].

1. Using itertools.chain() function

You can simply call itertools.chain(*iterables) to flatten a list of lists, as shown below:

Download  Run Code

 
This can also be done using itertools.chain.from_iterable(iterable), which doesn’t require unpacking the list.

Download  Run Code

2. Using sum() function

You can also use the built-in function sum(iterable[, start]) with start value as an empty list.

Download  Run Code

3. Using += operator

Python supports list operations like concatenation with the help of the + operator. To join chained input, you can either use the + or += operator as following:

Download  Run Code

4. Using List Comprehension

Another common solution is to use list comprehensions. This can be easily achieved using the extend() function, as demonstrated below:

Download  Run Code

 
Here’s how you can do using nested list comprehensions.

Download  Run Code

5. Using reduce operation

Another plausible way to flatten a list is to reduce with the add() or concat() function, as shown below:

Download  Run Code

 
Here’s another variation that uses the custom add function:

Download  Run Code

 
Alternatively, you can use the lambda expression to write small functions. Lambda takes several parameters and an expression combining these parameters and creates an anonymous function that returns the value of the expression:

Download  Run Code

That’s all about flattening a list of lists in Python.

 
Also See:

Join multiple lists in Python