Sub topic 7
Recursion on Lists and Strings
This chapter assumes you can read Python functions, know what a base case and a recursive case are, and can follow a trace through the call stack. It applies those ideas to sequences: lists and strings.
The First-and-Rest Pattern
A list can be described recursively. It is either empty, or it is a first element followed by a smaller list. Strings have the same shape. That definition gives you a template you can reuse:
- Base case: the sequence is empty (or has one element). Return the answer directly.
- Recursive case: handle the first element yourself and give the rest to a recursive call.
Each call works on a sequence one element shorter, so every chain of calls reaches the empty case.
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
print(total([3, 1, 4])) # 8
print(reverse("abc")) # cbaIn total, assume the recursive call correctly sums the rest of the list. Then all you need to do is add the first element. In reverse, assume reverse(s[1:]) reverses the tail. Putting the first character at the end finishes the job.
Choosing the Base Case
Pick the smallest input whose answer you know without any work. For a sum, the empty list gives 0, the identity for addition. For reverse, a string of length 0 or 1 is already its own reverse. If you only handle len(s) == 1, the function breaks on "". Slicing an empty string returns another empty string, so the call chain never ends.
The Hidden Cost of Slicing
items[1:] builds a new list, and copying it takes time proportional to its length. Over n calls that adds up to O(n²) work for a task that should take O(n). To avoid the copies, pass an index instead:
def total_from(items, i=0):
if i == len(items):
return 0
return items[i] + total_from(items, i + 1)
print(total_from([3, 1, 4])) # 8The base case is now "the index has reached the end", and progress means increasing i. The logic is the same, but no copies are made.
| Approach | Base case | Extra cost per call |
|---|---|---|
| Slicing `items[1:]` | `not items` | Copies the rest of the list |
| Index `i + 1` | `i == len(items)` | Constant |
Exercise
Write a recursive function count_char(s, c) that returns how many times character c appears in string s, using the first-and-rest pattern.
Show answer
def countchar(s, c): return 0 if not s else (1 if s[0] == c else 0) + countchar(s[1:], c). The base case is the empty string, which returns 0. The recursive case counts the first character and adds the count for the rest.
Exercise
What happens if reverse uses only if len(s) == 1: return s as its base case and is called with an empty string?
Show answer
The base case never matches, because "" has length 0, and ""[1:] is still "". The function calls itself on the same input forever, until Python raises RecursionError.