Computer >> Computer tutorials >  >> Programming >> Python

How to flatten a shallow list in Python?


A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops.

lst = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
flatlist = []
for sublist in lst:
   for item in sublist:
      flatlist.append(item)
print (flatlist)

A more compact and Pythonic solution is to use chain() function from itertools module.

>>> lst  =[[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
>>> import itertools
>>> flatlist = list(itertools.chain(*lst))
>>> flatlist
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]