Skip to content

Create a flat list out of a list of lists in Python

Let’s take a list of lists.

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

To merge this lists to a flat list you can use the following ways.

itertools.chain()

import itertools

list2d = [[1,2,3], [4,5,6], [7], [8,9]]
merged = list(itertools.chain(*list2d))
Advertisements

functools.reduce()

from functools import reduce
list2d = [[1,2,3], [4,5,6], [7], [8,9]]
reduce(lambda x, y: x+y, list2d)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

list.extend()

list2d = [[1,2,3], [4,5,6], [7], [8,9]]
out = []
for sublist in list2d:
    out.extend(sublist)
See also  Reading and Writing XML Files in Python with Pandas

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.