Search code examples
pythonlist-comprehension

Python list of lists to one dimensional using comprehension


What would be the syntax to convert this loop into one line comprehension operator?

lst = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12]
]

all_records = []
for entry in lst:
    all_records.extend(entry)

#[1, 2, 3, 3, 0, 1, 5, 2, 5, 10, 11]

When i am doing

all_records = [entry for entry in lst]

it gives

[[1, 2, 3], [3], [0, 1, 5], [2, 5, 10, 11]]

Solution

  • You might flatten 2D list using following comprehension

    lst = [[1,2,3],[4,5,6],[7,8,9]]
    flat = [j for i in lst for j in i]
    print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]