Reputation: 13
I am asked to make a function that sums the elements in each tuple
data = [(1,2), (3, 4, 5), (10, 20, 30, 40)]
print(tuple_sums(data))
The result must be
[3, 12, 100]
My wrong answer is below. It can only return one sum of the tuple:
def tuple_sums(tuples):
"""returns a list containing the sums"""
thesum = 0
for i in tuples:
thesum = thesum + i
return thesum
How can I return a list of sums instead of just one sum?
Upvotes: 1
Views: 56
Reputation: 198324
List comprehensions are a cool feature:
[sum(x) for x in data]
# => [3, 12, 100]
Upvotes: 1