Why does a recursive search that only recurses on L[1:] find 1 in [2, 5, 8, 1] but miss it in [2, 1, 5, 8] — and how do print statements expose the skipped element?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Here is the tempting first version of the membership test, with one extra line at the very top of the body so that every call announces the list it is currently examining:
## incorrect def in_list(L, e): print(L) if len(L) == 1: return L[0] == e else: return in_list(L[1:], e)
Someone runs in_list([7, 3, 9, 4], 9). Assign to trace a list of lists: the value each call prints, in the order the calls happen.
The wrong in_list that only checks the last element
Write the version whose else branch is bare return in_list(L[1:], e), and record both results, [2, 5, 8, 1] giving True for 1 and [2, 1, 5, 8] giving False.
Print statements inside the recursive function
Add a print of L and e at the top of the function and list the four lines it produces for [2, 1, 5, 8]: the full list, [1, 5, 8], [5, 8], [8].
The fixed version and its simplified three-branch form
Write the corrected in_list that returns True on L[0] == e before recursing, then the compact form with len(L) == 0 returning False as the base case.
One return type across every branch
State the rule that every return in a recursive function hands back the same type, and record that total_recur returns numbers throughout while in_list returns Booleans throughout.