Why is the sum function in python not working?
Question:
This is my code. I want add the total of the list cost, so the code will return £140, but it is not working. I want the £ sign to be in front of the sum of the cost so the user will know what the program is displaying.
cost = [['Lounge', 70], ['Kitchen', 70]]
print(cost)
print("£", sum(cost))
It returns this error message:
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I have looked online, but none of these results have helped me:
sum a list of numbers in Python
Answers:
Do this:
print("£", sum(c[1] for c in cost))
It’s basically a condensed version of this:
numbers = []
for c in cost:
numbers.append(c[1])
print("£", sum(numbers))
Functional solution:
from operator import itemgetter
print("£", sum(map(itemgetter(1), cost)))
Each element in cost
is a two-element tuple. You’d have to extract the numeric one, e.g., by using a list comprehension:
print("£" + str(sum(i[1] for i in cost)))
This is my code. I want add the total of the list cost, so the code will return £140, but it is not working. I want the £ sign to be in front of the sum of the cost so the user will know what the program is displaying.
cost = [['Lounge', 70], ['Kitchen', 70]]
print(cost)
print("£", sum(cost))
It returns this error message:
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I have looked online, but none of these results have helped me:
sum a list of numbers in Python
Do this:
print("£", sum(c[1] for c in cost))
It’s basically a condensed version of this:
numbers = []
for c in cost:
numbers.append(c[1])
print("£", sum(numbers))
Functional solution:
from operator import itemgetter
print("£", sum(map(itemgetter(1), cost)))
Each element in cost
is a two-element tuple. You’d have to extract the numeric one, e.g., by using a list comprehension:
print("£" + str(sum(i[1] for i in cost)))