Flattening a List of Lists in Python

Sometimes you have a list of lists and you just need a list. In my case, I have a list of texts within which is a list of sentences. But all I really need is the list of sentences. To peel off the additional layer of listiness, use the following list comprehension.

flattenedList = [[t for t in l if None not in t] for l in test]

And if that doesn’t work, try flattening:

import itertools
flat_list = list(itertools.chain(*regular_list))

UPDATE: some better code using itertools:

from itertools import chain

flattened = chain.from_iterable(iterable)

Leave a Reply