Implement sum_list(lst)
Write a recursive Python function that returns the sum of all numbers in a list. This problem introduces list recursion — peeling off the first element each call until the list is empty. Your code runs directly in the browser.
The problem
Use list slicing to reduce the problem each step. In Python, lst[0] is the first element and lst[1:] is a new list containing everything after it. The base case is an empty list, which has a sum of zero.
sum_list([5]) = 5 + sum_list([]) = 5
sum_list([1, 2, 3]) = 1 + sum_list([2, 3])
= 1 + 2 + sum_list([3])
= 1 + 2 + 3 + sum_list([]) = 6
Your function must pass these tests:
- sum_list([]) → 0
- sum_list([5]) → 5
- sum_list([1, 2, 3]) → 6
- sum_list([10, 20, 30, 40]) → 100
- sum_list([4, 7, 2, 9, 1]) → 23
Write your solution below, then click Run Tests:
Hints
Hint 1 — List slicing refresher
lst[0] gives the first element. lst[1:] gives a new list with the first element removed. If lst = [4, 7, 2], then lst[0] is 4 and lst[1:] is [7, 2].
Hint 2 — The recursive relationship
The sum of a non-empty list is lst[0] + sum_list(lst[1:]). Each call passes a list that is one element shorter, eventually reaching the empty list.
Hint 3 — Full solution
def sum_list(lst):
if not lst:
return 0
return lst[0] + sum_list(lst[1:])