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
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
import itertools
sum(itertools.chain.from_iterable([[1,2],[3,4],[5,6]]))
itertools.chain flattens one level of iterable (which is all you need here), so sum gets the list with the sublists broken out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With