Can't sum a list of strings in Python?

1.1k views Asked by At

I just want to print the length and sum of array values, that I input into the list.

Here is my code:

arr = list()
for x in range(1,6):
    print("Enter num ", x ," :")
    name = input()
    arr.append(name)
print ("ARRAY: ",arr)
l = len(arr)
s = sum(arr)
print (int(l,s))

And the output is:

ARRAY:  ['4', '2', '3', '4', '6']                                                                                                                                                  
Traceback (most recent call last):                                                                                                                                                 
  File "main.py", line 8, in <module>                                                                                                                                              
    s = sum(arr)                                                                                                                                                                   
TypeError: unsupported operand type(s) for +: 'int' and 'str'
2

There are 2 answers

1
Nathan On

Try this instead:

arr = list()
for x in range(1,6):
    print("Enter num ", x ," :")
    name = int(input())
    arr.append(name)
print ("ARRAY: ",arr)
l = len(arr)
s = sum(arr)
print (l,s)
0
ruohola On

Your code has two issues.

  • input returns a string, so you need to cast it to a integer before, you can sum the values.

  • This print (int(l,s)) doesn't really make any sense. If you look at the documentation of int, you can see that you are passing s as the base for the function, but it will fail, since the base can only be specified if the first agument is a string.

Here's a fixed version. I also used a f-string to place x in the input prompt:

arr = list()
for x in range(1, 6):
    name = int(input(f"Enter num {x}: "))
    arr.append(name)
print("ARRAY: ", arr)
l = len(arr)
s = sum(arr)
print(l, s)