user1816377 user1816377 - 3 months ago 21
Python Question

sum for list of lists

I'm looking for method in python to sum a list of list that contain only integers.
I saw that the method

sum()
works only for list but not for list of list.
There is anything fit for me?

thank you

Answer

You can use sum() with a generator expression here:

In [18]: lis = [[1, 2], [3, 4], [5, 6]]

In [19]: sum(sum(x) for x in lis)
Out[19]: 21

or:

In [21]: sum(sum(lis, []))
Out[21]: 21

timeit comparisons:

In [49]: %timeit sum(sum(x) for x in lis)
100000 loops, best of 3: 2.56 us per loop

In [50]: %timeit sum(map(sum, lis))
100000 loops, best of 3: 2.39 us per loop

In [51]: %timeit sum(sum(lis, []))
1000000 loops, best of 3: 2.21 us per loop

In [52]: %timeit sum(chain.from_iterable(lis))       # winner 
100000 loops, best of 3: 1.43 us per loop

In [53]: %timeit sum(chain(*lis))
100000 loops, best of 3: 1.55 us per loop