8

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)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user1275189
  • 97
  • 1
  • 1
  • 2

7 Answers7

13

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

numlist = [float(x) for x in numlist]
Zenon
  • 1,481
  • 12
  • 21
10

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)
...
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
4

You are adding up strings, not numbers, which is what your error message is saying.

Convert every string into its respective 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 dividing, as float(1/2) = float(0) = 0.0, which isn't what you want.

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

numlist = map(float, numlist)
Blender
  • 289,723
  • 53
  • 439
  • 496
0

You can try this.

reduce(lambda x,y:x+y, [float(x) for x in distance])
sth
  • 222,467
  • 53
  • 283
  • 367
0

Convert the string input to a 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)
DataCruncher
  • 850
  • 7
  • 11
0

For Python 2.7

numlist = map(int,raw_input().split(","))
s = sum(numlist)
l = len(numlist)
m = float(s/l)
print("mean:"+ str(m))
Marshall Davis
  • 3,337
  • 5
  • 39
  • 47
Pramodya Abeysinghe
  • 1,098
  • 17
  • 13
0

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

franka
  • 1,867
  • 3
  • 17
  • 31