arr.rsplit(',', len(arr))
print sum(arr)
If I input the string of "1,2,3,4", the first line splits it in a list of 1,2,3,4. But when I print the sum it does not work I get an error message.
In your case your splitting the string but the result is not assigned again to arr so your variable arr value is not getting changed it remains the string, so while you apply sum(arr) it is giving an error. But if you assign it to arr the type of split elements is <class 'str'> so convert it into integer
I trying to use split instead of rsplit Solution in Python 3 :
arr = "1,2,3,4"
arr = map(int,arr.split(','))
print(sum(arr))
Output : 10
It will convert each element to integer and then take the sum. But if you try to print arr : print(arr) after the map method it gives output : <map object at 0x7f90c081acc0> So convert arr to list to access the elements So instead of arr = map(int,arr.split(',')) give arr = list(map(int,arr.split(',')))
If you want to use rsplit then Solution (in python 3):
arr = "1,2,3,4"
arr = list(map(int,arr.rsplit(',', len(arr))))
print(sum(arr))
The best way to sum your array is (you need to convert your array elements to be a floating point number, not a string):
i=0
for a in arr.split(','): i=i+float(a) #use int() if you want integers
print i
With your less efficient syntax this would simply be:
i=0
for a in arr.rsplit(',', len(arr)): i=i+float(a) #use int() if you want integers
print i
Hope this helps. Check out this reference on types of variables
You need to split then convert the result to integers before you can sum.
arr_list = arr.split(',')
result = sum(int(i) for i in arr_list)
rsplitoversplit, and passing the second argument when you don't need to limit the number of splits? Also, you have a list of strings, not integers, even if the strings contain textual representations of integers.