上官林源
上官林源

Reputation: 19

Sum a list of decimals in Python

I was unsuccessfully trying to sum a list of decimals as follows.

q=(['0.50000', '0.56250', '0.50000', '0.50000'])
    
sum(q)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Upvotes: 0

Views: 9259

Answers (6)

Radical Ed
Radical Ed

Reputation: 189

Decimal numbers can be represented precisely with decimal.Decimal type.

from decimal import Decimal

q = ['0.50000', '0.56250', '0.50000', '0.50000']
sum(map(Decimal, q))

Decimal('2.06250')

Upvotes: 1

user459872
user459872

Reputation: 24797

sum function uses default start value as 0.

>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

So adding a int object with a string object will raise TypeError.

>>> 0 + '0.50000'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

In order to fix this, you can convert the string object into float object first and then apply the sum function.

Upvotes: 0

superb rain
superb rain

Reputation: 5521

Someone should post the imho proper version (see comments below):

>>> sum(map(float, q))
2.0625

Upvotes: 1

Ritesh
Ritesh

Reputation: 25

q=([0.50000, 0.56250, 0.50000, 0.50000])
sum(q)

or

q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum([float(x) for x in q])

Upvotes: 0

The.B
The.B

Reputation: 381

you can do it like this:

q=(['0.50000', '0.56250', '0.50000', '0.50000'])
result = 0 # create a variable wich will store the value.

for i in q: # loop over your elements
    result += float(i) # cast your temp variable (i) to float and add each element to result. 
print(result) # escape the loop and print the result variable.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117951

You have a list of str so first you have to convert them to float, which you can do using a generator expression within sum.

>>> sum(float(i) for i in q)
2.0625

Upvotes: 5

Related Questions