Skip to the content

Recursion with lists

Python · Unit 11: Recursion

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so the function adds up the whole list.

  3. 3. Find the bug

    This program should print 15. Which line has the bug?

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    Fill in the blank so it returns the largest number.

  6. 6. Multiple choice

    Why is the base case of largest a one-item list and not []?

  7. 7. Find the case that fails

    largest(nums) should return the biggest number in the list, or None if the list is empty. Which call does it fail on?

  8. 8. Put the lines in order

    Put the function in order. It tells you whether x is in the list.

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →