Welcome back to another edition of the How to Python series. This time I want to sum elements of two lists in Python. I got the inspiration for thi...
For further actions, you may consider blocking this person and/or reporting abuse
Maybe you can add benchmarks to the examples, to have an idea about costs.
There's an example that won't work:
this does not actually work:
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:
And this is the intermediate iterable generated by
zip
:Sum though works only on a list of numbers, so it will break on the second tuple. You can quickly see it by executing:
The third example works because
operator.add
it's just the functional version of the+
operator, which does:Hope this helps :)
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.