avatarShweta Lodha

Summarize

5 Ways To Flatten A List In Python

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

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 nested loop (a.k.a. loop inside another loop) which is not considered as a good practice. So, let’s move on to next 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 += and it will give you 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 5 ways. In case of any doubts, please feel free to check out my video recording:

Python
Python3
Programming
Tutorial
Beginner
Recommended from ReadMedium