Editor

Python Program to Find the Sum of a List Using Recursion

Beginner · Recursion

Adding up a list is usually done with a loop or `sum()`, but it is also a good first exercise in recursion. The sum of a list is its first number plus the sum of everything after it, and the sum of an empty list is 0. This program turns those two facts into a function that calls itself.

Program

sum_of_list_using_recursion.py
def list_sum(numbers):
# Base case: an empty list adds up to 0
if len(numbers) == 0:
return 0
# Recursive step: the first number plus the sum of the rest
return numbers[0] + list_sum(numbers[1:])
numbers = [4, 8, 15, 16, 23, 42] # or: numbers = [int(x) for x in input("Numbers: ").split()]
print("List:", numbers)
print("Sum using recursion:", list_sum(numbers))
print("Check with sum():", sum(numbers))
print("Sum of an empty list:", list_sum([]))
Output
List: [4, 8, 15, 16, 23, 42]
Sum using recursion: 108
Check with sum(): 108
Sum of an empty list: 0

How it works

  1. The base case is the empty list, which adds up to 0, and every call works on a shorter list, so the calls always reach it.
  2. The recursive step adds the first number, numbers[0], to the sum of the rest of the list, numbers[1:].
  3. For [4, 8, 15] this is 4 plus the sum of [8, 15], which is 8 plus the sum of [15], which is 15 plus the sum of [], which is 0, giving 27.
  4. The last two lines check the answer against the built-in sum() and show the empty case.

Other ways to write it

Using an index instead of slicing

Using an index instead of slicing
def list_sum(numbers, i=0):
if i == len(numbers): # base case: past the last item
return 0
return numbers[i] + list_sum(numbers, i + 1)
numbers = [4, 8, 15, 16, 23, 42]
print("Sum:", list_sum(numbers))
Output
Sum: 108

numbers[1:] makes a new, shorter copy of the list on every call, while passing a position i walks along the same list without copying it.

Summing a nested list

Summing a nested list
def nested_sum(items):
total = 0
for item in items:
if isinstance(item, list):
total += nested_sum(item) # a list inside: add up its numbers too
else:
total += item
return total
data = [1, [2, 3], [4, [5, 6]], 7]
print("Nested list:", data)
print("Sum:", nested_sum(data))
Output
Nested list: [1, [2, 3], [4, [5, 6]], 7]
Sum: 28

Recursion really pays off when lists are nested to any depth: whenever an item is itself a list, the function calls itself on it, which sum() alone cannot do.

Try it yourself

Write a recursive list_max(numbers) that finds the largest number in the same way.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises