Alec_ccc
Alec_ccc

Reputation: 83

Python: How to use the "sum" function to calculate the sum of numbers in a list?

I'm trying to calculate the sum of multiple numbers in one list, but there always appears an error. These numbers are readed from a txt.

Numbers:

19.18,29.15,78.75,212.10

My code:

infile = open("January.txt","r")
list = infile.readline().split(",")
withdrawal= sum(list)

Error:

withdrawal= sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Upvotes: 0

Views: 211

Answers (2)

Anshika Singh
Anshika Singh

Reputation: 1044

The elements of the list are in str format. When they are converted into int or float format, then the sum function will return the sum of the list.

This can be done using the map function as following:

liss=map(float,lis)

Hence :

f=open("January.txt", "r")
lis = f.readline().split(",")
liss=map(float,lis)
withdrawal= sum(liss)
print(withdrawal)

This will produce the desired output.

Hope this was helpful!

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117866

You would need to convert each element from str to float, you can do this with a generator expression.

with open("January.txt","r") as infile:
    data = infile.readline().split(",")
    withdrawal = sum(float(i) for i in data)

Upvotes: 2

Related Questions