Flatten an irregular list of lists
Using generator functions can make your example a little easier to read and probably boost the performance.
def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, basestring): for sub in flatten(el): yield sub else: yield el
I used the Iterable ABC added in 2.6.
In Python 3, the
basestring is no more, but you can use a tuple of
bytes to get the same effect there.
yield from operator returns an item from a generator one at a time. This syntax for delegating to a subgenerator was added in 3.3
from collections.abc import Iterabledef flatten(l): for el in l: if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el