How to make a flat ...
 
Share:
Notifications
Clear all

How to make a flat list out of a list of lists?


Neha
 Neha
(@asha)
Member Admin
Joined: 4 years ago
Posts: 31
Topic starter  

Is there a shortcut to make a simple list out of a list of lists in Python?

I can do it in a for loop, but maybe there is some cool "one-liner"? 😎 


myTechMint and Govind liked
Quote
Topic Tags
myTechMint
(@mytechmint)
Member Moderator
Joined: 4 years ago
Posts: 52
 

Using Pandas you can do this 

>>> from pandas.core.common import flatten
>>> l = [[1,2,3], [4,5], [6]]
>>> list(flatten(l))
>>> [1, 2, 3, 4, 5, 6]

OR

Using Itertools you can do this

>>> import itertools
>>> l = [[1,2,3], [4,5], [6]]
>>> flatten = itertools.chain.from_iterable
>>> list(flatten(l))
>>> [1, 2, 3, 4, 5, 6]

Neha liked
ReplyQuote