Reputation: 51
I am trying to use sum() function in my code, but there is an error, which i did not understand why. How can i solve this problem
my code should add up tuples of a list so the output should be like this
the input:
a = [(1, 2, 3), (4, 5, 6)]
the output:
(5, 7, 9)
this is my code
a = [(1, 3, 5), (2, 3, 5), (3, 3, 5), (4, 3, 5)]
a = iter(a)
b = next(a)
for x in a:
b = sum(b, x)
print(b)
The error is:
TypeError: can only concatenate tuple (not "int") to tuple
Upvotes: 0
Views: 68
Reputation: 6359
This can be done using the zip
builtin function:
[sum(x) for x in zip(*a)]
Full console session:
>>> a = [(1, 2, 3), (4, 5, 6)]
>>> list(zip(*a)) # "Make an iterator that aggregates elements from each of the iterables"
[(1, 4), (2, 5), (3, 6)]
>>> [sum(x) for x in zip(*a)]
[5, 7, 9]
>>>
Upvotes: 4