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

I am doing homework, and I need to use the sum () and len () functions to find the average from the list of input numbers, when I tried to use sum () to get the sum of the list, I received a TypeError error: unsupported operand type for +: 'int' and 'str'. Below 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) 
+8
function python list sum
source share
7 answers

The problem is that when you read from the input, you have a list of lines. You can do something like your second line:

 numlist = [float(x) for x in numlist] 
+13
source share

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

 numlist = numlist.split(",") numlist = map(int, numlist) s = sum(numlist) ... 
+9
source share

You add strings, not numbers, which is what your error message says.

Convert each line to the corresponding integer:

 numlist = map(int, numlist) 

And then take the average (note that I use float() differently than you do):

 arithmetic_mean = float(sum(numlist)) / len(numlist) 

You want to use float() before division, like float(1/2) = float(0) = 0.0 , which is not what you want.

An alternative would be to simply make them all float in the first place:

 numlist = map(float, numlist) 
+3
source share

Split returns you an array of strings, so you need to convert them to integers before using the sum function.

0
source share

You can try this.

 reduce(lambda x,y:x+y, [float(x) for x in distance]) 
0
source share

Convert string input to list of float values. Here is the updated code.

 numlist = list(map(int,input("Enter a list of number separated by commas: ").split(','))) l = len(numlist) s = sum(numlist) print("mean :",s/l) 
0
source share

For Python 2.7

 numlist = map(int,raw_input().split(",")) s = sum(numlist) l = len(numlist) m = float(s/l) print("mean:"+ str(m)) 
0
source share

All Articles