[python] Summing elements in a list

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.

This question is related to python list sum

The answer is


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

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.


>>> 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

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))

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

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!


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to sum

Iterating over arrays in Python 3 Get total of Pandas column Pandas: sum DataFrame rows for given columns How to find sum of several integers input by user using do/while, While statement or For statement SQL Sum Multiple rows into one Python Pandas counting and summing specific conditions SELECT query with CASE condition and SUM() Using SUMIFS with multiple AND OR conditions How to SUM parts of a column which have same text value in different column in the same row how to count the total number of lines in a text file using python