Monday, February 16, 2009

Merging lists (or any sequences) in Python

When writing Python programs, I often need to merge a list of lists into a single list. For example:

[[1, 2, 3], [4, 5], [6, 7]] -> [1, 2, 3, 4, 5, 6, 7]


Looking around on the Internet, I have not come across any solution better than the one I always use:

>>> def mergeseq( *lists ):
... return reduce( lambda x, y: x + y, lists )
...
>>> mergeseq( [1, 2, 3], [4, 5], [6, 7] )
[1, 2, 3, 4, 5, 6, 7]
>>> mergeseq( *[['a', 'b'], ['c'], ['d', 'e']] )
['a', 'b', 'c', 'd', 'e']


If you know of any better solutions, let me know. The idea behind my solution is to use the reduce builtin, and the fact that the addition ('+') operator in Python works as expected for lists.

Note that really, all that mergeseq is doing is to apply the addition operator to the current result and the next element in the input. So, this will work too:

>>> mergeseq( 1, 2, 3, 4 )
10