python list comprehensions; compressing a list of lists? python list comprehensions; compressing a list of lists? python python

python list comprehensions; compressing a list of lists?


You can have nested iterations in a single list comprehension:

[filename for path in dirs for filename in os.listdir(path)]

which is equivalent (at least functionally) to:

filenames = []for path in dirs:    for filename in os.listdir(path):        filenames.append(filename)


>>> from functools import reduce>>> listOfLists = [[1, 2],[3, 4, 5], [6]]>>> reduce(list.__add__, listOfLists)[1, 2, 3, 4, 5, 6]

I'm guessing the itertools solution is more efficient than this, but this feel very pythonic.

In Python 2 it avoids having to import a library just for the sake of a single list operation (since reduce is a built-in).


You can find a good answer in itertools' recipes:

def flatten(listOfLists):    return list(chain.from_iterable(listOfLists))

(Note: requires Python 2.6+)