Open In App

Sum all Items in Python List without using sum()

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, typically the sum() function is used to get the sum of all elements in a list. However, there may be situations where we are required to sum the elements without using the sum() function. Let's explore different methods to sum the items in a list manually.

Using for loop

Using a for loop is another simple way to sum all items in list without using sum(). We can iterate through each item in the list, adding the items to a running total.

Python
#Input List

a = [1, 2, 3, 4, 5] 

# Initialize a variable to hold the total sum
total = 0

# Loop through each item in the list and add it to the total
for num in a:
    total += num

print(total)  

Output
15

Explanation:

  • We initialize a variable total to 0.
  • We loop through each item in the list, adding the item to total.
  • After the loop, total holds the sum of all items in the list

Let's explore some more methods and see how we can sum all items in python list without using sum().

Using reduce from functools

Python's reduce() function from the functools module can also be used to sum the items in a list. The reduce function applies a binary function cumulatively to the items in the list.

Python
from functools import reduce
a = [1, 2, 3, 4, 5]

# Use reduce to sum the elements in the list
total = reduce(lambda x, y: x + y, a)

print(total)  

Output
15

Explanation:

  • We import the reduce() function from the functools module.
  • The reduce function takes a lambda function that adds two numbers and applies it cumulatively to the items in the list.

Using a recursive function

For a more advanced solution, we can use recursion. A recursive function calls itself until the base condition is met, summing the elements in the list.

Python
a = [1, 2, 3, 4, 5]

# Recursive function to sum the list
def recursive_sum(a):
    if len(a) == 0:
        return 0
    else:
        return a[0] + recursive_sum(a[1:])

# Call the function and print the result
total = recursive_sum(a)
print(total)  

Output
15

Explanation:

  • recursive_sum function calls itself with the rest of the list (excluding the first element) until the list is empty.
  • base case is when the list is empty, at which point it returns 0.
  • The sum is calculated by adding the first element of the list to the result of the recursive call on the remaining list.

Next Article
Practice Tags :

Similar Reads