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(in
If you prefer a less functional style, you can use a generator expression
result = sum(int(x) for x in numbers))
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.