10 Most Frequently Asked Python List Questions on Stack Overflow | by Soner Yıldırım | Jul, 2023


2. How do I make a flat list out of a list of lists?

The following drawing illustrates what is being asked in this question:

Flattening a list of lists (image by author)

You can do this conversion by using a list comprehension as follows:

# using list comprehension
mylist = [
[1, 5, 3],
[4, 2, 1],
[5, 6]
]

myflatlist = [item for sublist in mylist for item in sublist]

print(myflatlist)

# output
[1, 5, 3, 4, 2, 1, 5, 6]

The list comprehension above can also be written as nested for loops. It’s more intuitive and easier to understand but list comprehension is more performant especially when working with large lists.

# using for loops
mylist = [
[1, 5, 3],
[4, 2, 1],
[5, 6]
]

myflatlist = []

for sublist in mylist:
for item in sublist:
myflatlist.append(item)

print(myflatlist)

# output
[1, 5, 3, 4, 2, 1, 5, 6]

If you’re using Pandas, the explode function makes this flattening operation quite easy but you need to convert the list to a Pandas series first. If you want the final output to be a list, then you can convert the output of the explode function to a list using the list constructor.

# using the explode function
import pandas as pd

myflatlist = list(pd.Series(mylist).explode())

print(myflatlist)

# output
[1, 5, 3, 4, 2, 1, 5, 6]



Source link

Leave a Comment