Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use sum() function for a list in Python?

I am doing my homework and it requirers me to use a sum () and len () functions to find the mean of an input number list, when I tried to use sum () to get the sum of the list, I got an error TypeError: unsupported operand type(s) for +: 'int' and 'str'. Following is my code:

numlist = input("Enter a list of number separated by commas: ")

numlist = numlist.split(",")

s = sum(numlist)
l = len(numlist)
m = float(s/l)
print("mean:",m)
like image 728
user1275189 Avatar asked Mar 17 '12 01:03

user1275189


People also ask

How do you sum parts of a list in Python?

Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.

What does sum () do in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.


1 Answers

The problem is that you have a list of strings. You need to convert them to integers before you compute the sum. For example:

numlist = numlist.split(",")
numlist = map(int, numlist)
s = sum(numlist)
...
like image 112
Justin Ethier Avatar answered Oct 12 '22 23:10

Justin Ethier