Sub topic 7
Recursion on Lists and Strings
This chapter assumes you can read Python functions, know how list and string indexing and slicing work (items[0], items[1:]), and have met the base case, the recursive case, and the leap of faith from earlier chapters. Here those ideas are applied to the most common recursive inputs in everyday code: sequences.
The Head-and-Tail Model
A list or string can be seen as two parts. The head is the first element. The tail is everything after it. The tail is itself a list or string, just one element shorter. That shape matches recursion exactly:
- The base case is the empty sequence, or sometimes a sequence of length one.
- The recursive case handles the head directly and passes the tail to a recursive call.
Each call takes one element off, so the input shrinks by one per step and eventually reaches the base 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")) # cbaRead total with the leap of faith in mind. If total(items[1:]) correctly sums the tail, then adding the head gives the sum of the whole list. The empty list sums to 0, which is the identity value for addition. That choice matters. A base case that returns the identity of the combining operation (0 for +, 1 for *, "" for string concatenation, [] for list concatenation) lets the recursive case work without special cases.
Three Recipes for Sequence Recursion
Most recursive functions on sequences fall into one of three patterns. Knowing which one you need tells you what the base case returns and how the head and the recursive result are combined.
| Pattern | Question it answers | Base case returns | Combine step |
|---|---|---|---|
| Reduce | One value from all elements (sum, max, count) | Identity value, or the single element | `head OP recurse(tail)` |
| Transform | A new sequence of the same kind (map, filter, reverse) | Empty sequence | Build the result from the head and `recurse(tail)` |
| Search or test | A yes/no answer or a position | `False`, `True`, or `-1` | Return early when the head decides the answer |
Here is one example of each.
def count(items, target):
# Reduce: how many times target appears
if not items:
return 0
rest = count(items[1:], target)
return rest + 1 if items[0] == target else rest
def squares(items):
# Transform: a new list with each element squared
if not items:
return []
return [items[0] ** 2] + squares(items[1:])
def contains(items, target):
# Search: stop as soon as the answer is known
if not items:
return False
if items[0] == target:
return True
return contains(items[1:], target)
print(count([1, 2, 1, 1], 1)) # 3
print(squares([1, 2, 3])) # [1, 4, 9]
print(contains("hello", "l")) # TrueThe search pattern can return without recursing any further. Once contains finds the target, the remaining calls never happen. The reduce and transform patterns have to visit every element.
Shrinking From Both Ends
Not every problem removes only the head. A palindrome check compares the first and last characters, then recurses on the middle:
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("racecar")) # True
print(is_palindrome("abca")) # False
print(is_palindrome("")) # TrueEach call removes two characters, so an odd-length string ends at length 1 and an even-length string ends at length 0. The base case len(s) <= 1 covers both. If you wrote len(s) == 1 instead, every even-length palindrome would reach "", and s[0] would raise an IndexError.
The Hidden Cost of Slicing
items[1:] looks free, but in Python it builds a new list and copies every remaining element. For a list of length n, the calls copy n−1, n−2, ..., 1 elements, which adds up to about n²/2 copies. A function that should take linear time takes quadratic time. String slicing behaves the same way, and reverse also builds a new string with every +.
The fix is to pass an index instead of a slice. The list itself stays the same, and the index shows where the current "tail" begins:
def total_from(items, i=0):
if i == len(items):
return 0
return items[i] + total_from(items, i + 1)
def is_palindrome_idx(s, lo=0, hi=None):
if hi is None:
hi = len(s) - 1
if lo >= hi:
return True
if s[lo] != s[hi]:
return False
return is_palindrome_idx(s, lo + 1, hi - 1)
print(total_from([3, 1, 4])) # 8
print(is_palindrome_idx("racecar")) # True
print(is_palindrome_idx("abca")) # FalseThe logic is unchanged: the index i stands for the tail items[i:]. Now each call does a constant amount of work, so the whole function runs in O(n) time. The trade-off is readability. The slicing version shows the head-and-tail idea more plainly, which is why it shows up in teaching code. The index version is the one to use when inputs can be large.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `IndexError` on `items[0]` | Base case missing, or never reached for some lengths | Test `if not items` before indexing |
| `TypeError: can only concatenate list (not "int")` | Transform returned an element where a list was expected | Wrap the head: `[head] + rest` |
| Result is `None` | The recursive branch forgot `return` | Return the recursive call's result |
| Wrong answer for empty input | Base case returns a non-identity value, such as `1` for a sum | Return the identity of the combine operation |
| Function slows down sharply as input grows | Slicing copies the tail on every call | Pass an index instead |
The None bug is especially common in the search pattern:
def contains_buggy(items, target):
if not items:
return False
if items[0] == target:
return True
contains_buggy(items[1:], target) # result is thrown away
print(contains_buggy([1, 2, 3], 3)) # NoneThe deeper call does find 3 and returns True, but the caller throws that value away and returns None. Every path through a recursive function that produces a value needs a return.
Choosing the Base Case
Use the empty sequence as the base case by default. It handles empty input, and it usually makes the recursive case simpler. Switch to length one, or to a nonempty-only base case, when no sensible value exists for empty input. Maximum is the standard example, because an empty list has no maximum:
def maximum(items):
if len(items) == 1:
return items[0]
rest_max = maximum(items[1:])
return items[0] if items[0] > rest_max else rest_max
print(maximum([3, 7, 2])) # 7Calling maximum([]) fails, which matches the behavior of Python's built-in max([]). If you use a base case like this, write down that the function requires nonempty input. Callers should not have to find that out from a crash.
Exercise
Write a recursive function remove_all(items, target) that returns a new list with every occurrence of target removed, using the transform pattern. What does it return for remove_all([1, 2, 1, 3], 1)?
Show answer
Base case: if not items, return []. Recursive case: rest = remove_all(items[1:], target); return rest if items[0] == target else [items[0]] + rest. For [1, 2, 1, 3] with target 1 it returns [2, 3].
Exercise
Why does reverse("") return "" correctly, and what would go wrong if the base case were len(s) == 1 instead of len(s) <= 1?
Show answer
With len(s) <= 1, the empty string matches the base case and is returned unchanged. With len(s) == 1, reverse("") skips the base case and evaluates s[0] on an empty string, which raises IndexError. Nonempty strings would still work, because shrinking by one from length 1 or more always reaches length 1.
Exercise
The slicing version of total on a list of 1,000 elements copies roughly how many elements in total, and how many does total_from copy?
Show answer
The slices copy 999 + 998 + ... + 1, which is about 500,000 elements (n²/2). total_from copies none, because it passes the same list and an index, so its total work is proportional to 1,000.