DEV Community

Discussion on: How to Sum Elements of Two Lists in Python

Collapse
 
rhymes profile image
rhymes •

Maybe you can add benchmarks to the examples, to have an idea about costs.

There's an example that won't work:

all_devices = [sum(pair) for pair in zip(ethernet_devices, usb_devices)]

this does not actually work:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

The reason is the first item in your lists is an integer, not a list. The whole thing works in the manual examples because Python's + operator has meaning for two integers and for two lists.

Let's see what you're asking for a result:

[2, [7, 7], [2, 1], [8374163, 2314567], [84302738, 0]]

And this is the intermediate iterable generated by zip:

>>> [pair for pair in zip(ethernet_devices, usb_devices)]
[(1, 1), ([7], [7]), ([2], [1]), ([8374163], [2314567]), ([84302738], [0])]

Sum though works only on a list of numbers, so it will break on the second tuple. You can quickly see it by executing:

>>> sum(([7], [7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

The third example works because operator.add it's just the functional version of the + operator, which does:

>>> (1).__add__(1)
2
>>> ([7]).__add__([7])
[7, 7]

Hope this helps :)

Collapse
 
therenegadecoder profile image
Jeremy Grifski • • Edited

Good catch! I must have made a mistake when I was copying this article over. I’ll correct that section when I get a chance.

EDIT: After a closer look, I guess I just never tested that solution. Whoops! I referenced your great comment in the original post as well.