Last Updated: February 25, 2016
·
17.42K
· samer-meggaly

Python "sum" - Convert list-of-lists to a list

Some times you may face the case in which you have a list of lists (or tuples) as follows

lists_list = [ [1, 2], [3, 4], [5, 6] ]
tuples_list = [ (1, 2, 3), (4, 5, 6) ]

and you want to convert them into a single list as follows

alist = [1, 2, 3, 4, 5, 6]

You can use loops and comprehensions of course!

However, the built-in sum function in python can do this

for lists

alist = list(sum(lists_list, []))

for tuples

alist = list(sum(tuples_list, ()))

Hope this was a helpful tip,

1 Response
Add your response

A little more readable version might be:

from itertools import chain
list(chain(*lists_list))
list(chain(*tuples_list))

I say more readable because sum is using the specialized implementation of adding two lists (or tuples). Without knowledge of what's going on under the hood, this would likely confuse the reader. The hood is opened when mixing a list and a tuple as elements of the parent list:

>>> m = [[1, 2], (3, 4)]
>>> list(sum(m, []))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

However, this still work with chain as it only cares that the elements are iterables, not their types.

over 1 year ago ·