How does one extra type test turn a shallow my_rev into a five-line deep_rev that reverses arbitrarily nested lists all the way down?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
deep_rev reverses every level of nesting, descending into lists and stopping at anything that is not a list. Here is a list it has never seen:
[1, [2, 3], [[4, 5], 6]]
Work out what deep_rev hands back for it — on paper, in your head, one element at a time — and assign that result to deep_reversed as a plain list literal. No code, no calls: this one is a hand trace.
Hand-trace of a deep reversal
Reverse [[1, 2], 3, 4, [[5, 6], [7, 8]]] layer by layer, moving each front element to the end and flipping it, and land on [[[8, 7], [6, 5]], 4, 3, [2, 1]].
The type test type(L[0]) != list
Write the four-branch deep_rev, setting deep_rev(L[1:]) + [L[0]] for a non-list first element against deep_rev(L[1:]) + [deep_rev(L[0])] for a list one.
'One element' meaning one top-level element
Record that [[1]] counts as one element while [[5, 6], [7, 8]] counts as two, and that the square brackets around each concatenated piece hold the nesting in place.
The compacted version and other sequences
Write the five-line form starting if L == [], and note that these list patterns carry over to tuples and mostly to strings, deep reversal excepted.