Find the sum of all elements in a Python list

Problem:

To take and sum all the elements present in a Python integer or float numbers list.

Solution:

We have three different methods to achieve the solution. In this post, we will look at all three methods to sum the numbers in a list.

Option 1: Python Sum() Function:

Python has an inbuilt function sum(), which helps us take all the elements in a list and add them to return with the sum of elements. Let us see how to use the sum() function to add the values in a list from an example.

Code:

def getvalues(value):
    addlist = sum(value)
    return addlist
listofnumbers = [61,67,98,34]
print("Random Numbers:", listofnumbers)
print("Total sum is:", getvalues(listofnumbers))

Output:

Random Numbers: [61, 67, 98, 34]
Total sum is: 260

Option 2: For Loop Technique

In the looping technique, we will first assign an empty integer. Using for loop, we will take up the values from the list one by one, then store and add the values to attain the sum of all the elements in the list.

Code:

def getvalues(value):
    addlist = 0
    for i in value:
        addlist = addlist+i
    return addlist
listofnumbers = [56,94,23,12]
print("Random Numbers:", listofnumbers)
print("Total sum is:", getvalues(listofnumbers))

Output:

Random Numbers:  [56, 94, 23, 12]
Total sum is:  185

Option 3: Using Recursion

In this technique, instead of using the loop and add all the elements in the list, we would call the values recursively and decrement the length of the list during each iteration. We will then return the final value when the length of the list becomes Zero. Here in the below example, getvalues has taken two arguments (list and index of the list).

Code:

def getvalues(value,i):
    if i == 0:
        return value[i]
    return value[i] + getvalues(listofnumbers, i-1)
listofnumbers = [23,12,76,87]
print("Random Numbers:", listofnumbers)
print("Total sum is: ", getvalues(listofnumbers,len(listofnumbers)-1))

Output:

Random Numbers: [23, 12, 76, 87]
Total sum is:  198