Recursion with lists
Python · Unit 11: Recursion
- Full plan
- Python
- 9 exercises
A list is its first item plus the rest: nums[0] and nums[1:]. The rest is a shorter list.
In the end you get [], the empty list, which makes a good base case.
nums = [4, 7, 1]
print(nums[0])
print(nums[1:])
print([9][1:])Prints
4 [7, 1] []
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Fill in the blank so the function adds up the whole list.
3. Find the bug
This program should print 15. Which line has the bug?
4. Predict the output
What does this code print?
5. Complete the code
Fill in the blank so it returns the largest number.
6. Multiple choice
Why is the base case of
largesta one-item list and not[]?7. Find the case that fails
largest(nums)should return the biggest number in the list, orNoneif the list is empty. Which call does it fail on?8. Put the lines in order
Put the function in order. It tells you whether
xis in the list.9. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.