Summing elements in a list

PythonListSum

Python Problem Overview


Here is my code, I need to sum an undefined number of elements in the list. How to do this?

l = raw_input()
l = l.split(' ')
l.pop(0)

My input: 3 5 4 9 After input I delete first element via l.pop(0). After .split(' ') my list is ['5', '4', '9'] and I need to sum all elements in this list.

In this case the sum is 18. Please notice that number of elements is not defined.

Python Solutions


Solution 1 - Python

You can sum numbers in a list simply with the sum() built-in:

sum(your_list)

It will sum as many number items as you have. Example:

my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]

sum(my_list)
91

For your specific case:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']

sum(int(i) for i in data)
18

This will work for undefined number of elements in your list (as long as they are "numbers")

Thanks for @senderle's comment re conversion in case the data is in string format.

Solution 2 - Python

>>> l = raw_input()
1 2 3 4 5 6 7 8 9 10
>>> l = l.split()
>>> l.pop(0)
'1'
>>> sum(map(int, l)) #or simply sum(int(x) for x in l) , you've to convert the elements to integer first, before applying sum()
54

Solution 3 - Python

Python iterable can be summed like so - [sum(range(10)[1:])] . This sums all elements from the list except the first element.

>>> atuple = (1,2,3,4,5)
>>> sum(atuple)
15
>>> alist = [1,2,3,4,5]
>>> sum(alist)
15

Solution 4 - Python

You can also use reduce method:

>>> myList = [3, 5, 4, 9]
>>> myTotal = reduce(lambda x,y: x+y, myList)
>>> myTotal
21

Furthermore, you can modify the lambda function to do other operations on your list.

Solution 5 - Python

You can use sum to sum the elements of a list, however if your list is coming from raw_input, you probably want to convert the items to int or float first:

l = raw_input().split(' ')
sum(map(int, l))

Solution 6 - Python

You can use map function and pythons inbuilt sum() function. It simplifies the solution. And reduces the complexity.
a=map(int,raw_input().split())
sum(a)
Done!

Solution 7 - Python

def sumoflist(l):    
    total = 0    
    for i in l:
        total +=i
    return total

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrengView Question on Stackoverflow
Solution 1 - PythonLevonView Answer on Stackoverflow
Solution 2 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 3 - PythonSrikar AppalarajuView Answer on Stackoverflow
Solution 4 - PythonChappletonView Answer on Stackoverflow
Solution 5 - PythonunkulunkuluView Answer on Stackoverflow
Solution 6 - PythonShreyaa SridharView Answer on Stackoverflow
Solution 7 - PythonniksyView Answer on Stackoverflow