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
List: [4, 8, 15, 16, 23, 42] Sum using recursion: 108 Check with sum(): 108 Sum of an empty list: 0
How it works
- 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.
- The recursive step adds the first number,
numbers[0], to the sum of the rest of the list,numbers[1:]. - 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. - 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises