How can we make a flat list out of a list of lists? (Python List Comprehension)


How can we make a flat list out of a list of lists?

l = [[1,2,3],[3,4,5],[6,7,8]]

In order to achive this end, we can use for loops:

Method 1

flat_list = []

for  sub_list in l:

    for item in sub_list:

        flat_list.append(item)

And also we can use list comprehension, which is more efficient:

Method 2

flat_list = [item for sub_list in l for item in sub_list]

We can also use the itertools library:

Method3

import itertools

flat_list = list(itertools.chain(*l))

Comments

Popular posts from this blog

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

How to create a memory puzzle game with Python and Pygame (#005)

Introduction to multitasking with Python #001 multithreading (2020 tutorial)