-1

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

How do I add together integers in a list in python?

http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsCalculatingtheSumofaListofNumbers.html

Sum the second value of each tuple in a list

Community
  • 1
  • 1
User0123456789
  • 760
  • 2
  • 10
  • 25
  • "but none of these results have helped me" After reading the last result, what code did you try using? What happened when you tried it, and how was that different from what you wanted? – Karl Knechtel Jan 30 '23 at 07:09
  • It's only failing because you aren't providing an appropriate "base" value of `[]` in place of the default `0`. (Look at `sum(cost, [])`.) But you aren't trying to sum the correct iterable in the first place. – chepner Feb 18 '23 at 17:28

3 Answers3

1

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))
zondo
  • 19,901
  • 8
  • 44
  • 83
  • Thanks, it worked :) But can you explain it through so that I understand how it works? – User0123456789 Feb 12 '16 at 18:59
  • It is a shortcut for `lis = [] for c in cost: lis.append(c[1]) print("£", sum(lis))`. [Here](https://wiki.python.org/moin/Generators) is more information about generators. – zondo Feb 12 '16 at 19:55
1

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)))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Functional solution:

from operator import itemgetter

print("£", sum(map(itemgetter(1), cost)))
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36