Learn Python · lesson 50 of 60 · about 8 minutes
Recursion on Lists and Text
Use recursion to work through a list or a string one item at a time.
What you'll learn
- Split a list into its first item and the rest
- Add up a list recursively
- Reverse text with recursion
Phoebe's secret code
Sam and Phoebe send each other messages in a secret code: every word written backwards, so meet at noon becomes teem ta noon. The assistant does the coding with two recursive functions: reverse(word) turns one word round, a letter at a time, and code_words(words) codes the first word of the list and leaves the rest of the list to another call.
First item and the rest
A list can be seen as its first item plus the rest of the list. Slicing gives you both: items[0] and items[1:].
That makes lists a natural fit for recursion. The base case is usually the empty list: there's nothing left to do.
Adding up a list
def add_up(items):
if items == []:
return 0
return items[0] + add_up(items[1:])
print(add_up([4, 2, 7]))
print(add_up([]))Output
13
0Text works the same way
A string is its first letter plus the rest. To reverse it, reverse the rest and put the first letter on the end. The base case is the empty string, which is already reversed.
Reversing a word
def reverse(text):
if text == "":
return ""
return reverse(text[1:]) + text[0]
print(reverse("phoebe"))Output
ebeohpBuilding a new list
A recursive function can build a list as well as a number. Put the first item's answer in a list of its own, [...], and add the list the recursive call gives back for the rest. The empty list gives back [], so every list ends up joined together.
Shouting every word
def shout(words):
if words == []:
return []
return [words[0].upper()] + shout(words[1:])
print(shout(["hi", "phoebe"]))Output
['HI', 'PHOEBE']Tip
In real programs sum(items) or text[::-1] do these jobs in one go. Recursion earns its keep on problems loops find awkward, like the nested lists in the next lessons.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.