Reputation: 51
Having a list of numbers stored as strings how do I find their sum?
This is what I'm trying right now:
numbers = ['1', '3', '7']
result = sum(int(numbers))
but this gives me an error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
result = sum(int(numbers))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
I understand that I cannot force the list to be a number, but I can't think of a fix.
Upvotes: 2
Views: 17656
Reputation: 304127
If you prefer a less functional style, you can use a generator expression
result = sum(int(x) for x in numbers))
Upvotes: 5
Reputation: 142106
int(numbers)
is trying to convert the list to an integer, which obviously won't work. And if you had somehow been able to convert the list to an integer, sum(int(numbers))
would then try to get the sum of that integer, which doesn't make sense either; you sum a collection of numbers, not a single one.
Instead, use the function map
:
result = sum(map(int, numbers))
That'll take each item in the list, convert it to an integer and sum the results.
Upvotes: 8