Sum of a List in Python

This tutorial will be focussed to discuss different ways for how to find the sum of a list in python. So without further ado let’s get started.

1. By Using sum() Builtin Function

The sum() is the builtin function that takes an iterable as an argument and returns the total of it.

Let’s use it to find the sum of a list in python.

# program 1 to find the sum of a list in python

data = [8,6,9,4] # input list

# apply sum builtin function on a list
print("Sum :",sum(data))

Here is the output of above code.

Output

Output of using sum() builtin function to find sum of a list in python

2. By Using For-loop

In this code example, we have used for loop to find the sum of a list in python.

Here is the algorithm.

  • We first initialize an empty variable total to 0.
  • Then we iterate through each element of a list.
  • Then we increment the total by 1.
# program 2 to find the sum of a list in python

data = [8,6,9,4]

# variable to store value
total = 0

for i in data: # loop through the data
    total += i # add to total

print(total)

3. By Using While-loop

In the following code snippet, we have used the while loop to find the sum of all elements of a list.

Here is the algorithm.

  • We first initialize the total variable to 0.
  • Then grab the length of the data and set it to the variable l.
  • Then run the while-loop with the condition that l is greater than 0.
  • Inside the body of the while loop, we first add the element at index l-1 to the total then decrement the l by 1.
data = [8,6,9,4]

total = 0
l = len(data) # Grab the len of the data

while l > 0: # run the while loop until l is greater than 0
    total += data[l-1] # add element at index l-1 to the total
    l-=1 # decrease l by 1

print(total)

4. By Using Recursion

In the below code, we have used recursion technique of programming to find the sum of a list.

def find_sum(data,pointer):
    """
    Recursive function to find the sum of a list in python
    """
    if pointer == 0:
        return 0
    pointer -= 1
    return data[pointer] + find_sum(data,pointer)


data = [8,6,9,4]
s = find_sum(data,len(data))
print(s)

That’ wrap for this tutorial.

Leave a Reply