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

How to join list of lists in python?


There are different ways to flatten a list of lists. Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.

L1=[[1,2],[3,4,5],[6,7,8,9]]
flat=[]
for i in L1:
  for j in i:
    flat.append(j)
print (flat)

Another method is to use a generator function to yield an iterator and convert it to a list

def flatten(list):
  for i in list:
    for j in i:
      yield j


L1=[[1,2,3],[4,5],[6,7,8,9]]
flat=flatten(L1)
print (list(flat))

Most compact method is to use chain() method from itertools module

L1=[[1,2,3],[4,5],[6,7,8,9]]
import itertools
flat=itertools.chain.from_iterable(L1)
print (list(flat))

All the above codes produce a flattened list

[1, 2, 3, 4, 5, 6, 7, 8, 9]