Often you may have to flatten a list of lists or merge multiple lists into a single list in python. Obviously there are multiple ways to go about it. Here are three ways to flatten or merge lists in to a list.
Merge with “+” Operator”
If you have three separate lists like [1, 2, 3], [4, 5, 6], [7, 8, 9], you can merge in to a single list using + operator like
> [1, 2, 3] + [4, 5, 6] + [7, 8, 9] > [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that the use of “+” to merge lists preserves any duplicates present in multiple lists. For example, the duplicate “4” will be in the merged list.
> [1, 2, 3, 4] + [4, 5, 6] + [7, 8, 9] > [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
Flatten with “sum” Operator”
If you have a list of lists, we can use the sum operator to merge lists
> lol= [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > sum(lol , []) > [1, 2, 3, 4, 5, 6, 7, 8, 9]
Merging/Collapsing/Flattening a list of lists with list comprehensions
We can use list comprehensions in python to merge/collapse/flatten a list of lists.
> lol= [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [i for l in lol for i in l] > [1, 2, 3, 4, 5, 6, 7, 8, 9]