A Python Flatten Function

The Python library documentation for itertools has a recipe for a flatten function:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)

Pancakes by asolario on stock.xchng 


I couldn't memorize this because I was distracted by the use of the alternative init function, from_iterable. You can see that the normal init function doesn't give me what I want:
>>> list(itertools.chain([(1, 2), (2, 3)]))
[(1, 2), (2, 3)]
If I unpack the nested iterables by hand the normal init function does do what I want:

>>> list(itertools.chain((1, 2), (2, 3)))
[1, 2, 2, 3]


Which leads me to an alternative recipe for flatten that will be easier for me to remember, though it relies on an operator (*, an asterisk, a.k.a splat) that not everyone necessarily knows, likes or uses:

>>> def flatten(nestedIterable):
... return itertools.chain(*nestedIterable)
...
>>> list(flatten([(1, 2), (2, 3)]))
[1, 2, 2, 3]

Update 2014-08-25: My favorite approach to flattening in python is now to use the sum builtin with its start parameter.


>>> sum([[1, 2,], [2, 3]], [])
[1, 2, 2, 3]


comments powered by Disqus