5 Ways To Flatten A List In Python

There are many ways to flatten a list in Python, but in this article, I will mention my top five favorites.

5 Ways To Flatten A List In Python

Let’s get started.

Way 1

Loop over individual lists and use append to construct a single list

lst = [[1,2], [3,4,5]]
full_list = []
for ls in lst:
  for item in ls:
     full_list.append(item)
print(full_list)
#output: [1,2,3,4,5]

In this approach, we are using a nested loop (a.k.a. loop inside another loop), which is not considered a good practice. So, let’s move on to the following approach.

Way 2

Using extend function,

lst = [[1,2], [3,4,5]]
full_list = []
for ls in lst:
   full_list.extend(ls)
print(full_list)
#output: [1,2,3,4,5]

Similar to extend(…) function, you can also use +=, which will give you the same result.

full_list += ls

Way 3

Using List comprehension,

lst = [[1,2], [3,4,5]]
full_list = [item for ls in lst for item in ls]
print(full_list)
#output: [1,2,3,4,5]

Way 4

Using itertools,

import itertools
lst = [[1,2], [3,4,5]]
full_list = list(itertools.chain.from_iterable(lst))
print(full_list)

Way 5

Using functools,

import operator
import functools
lst = [[1,2], [3,4,5]]
full_list = functools.reduce(operator.iconcat,lst,[])
print(full_list)
#output: [1,2,3,4,5]

I hope you enjoyed learning all these five ways. In case of any doubts, please feel free to check out my video recording.


Similar Articles