Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 718
user1816377 Avatar asked Jan 31 '26 08:01

user1816377


2 Answers

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
like image 138
Ashwini Chaudhary Avatar answered Feb 02 '26 00:02

Ashwini Chaudhary


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.

like image 45
Marcin Avatar answered Feb 02 '26 00:02

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!