Loading...
A non-empty list can be viewed as its first element and the list of remaining elements. Handle the empty case explicitly before taking a head or recursing on a tail.
What you'll be able to do
For [4,3,5], the head is the element 4 and the tail is the list [3,5]. The tail of a one-element list is empty, not an absent numerical value. The empty list has length zero and has no head under the ordinary model.
A recursive list algorithm can stop at empty and otherwise process the head followed by the tail. This structure follows the data definition. Check the empty case before accessing index zero in a Python demonstration, because an empty list does not provide that position.
Prepending x constructs a list with x before the existing elements; appending places it after them. A functional style can return a new list rather than changing the original in place. Python [x]+values and values+[x] illustrate these meanings without claiming to be constant-time linked-list operations.
An immutable linked-list model can share a tail efficiently, while Python slicing creates a new outer list. Therefore, repeated tail slicing can add copying costs. Distinguish the abstract operation from the representation used to demonstrate it, especially when analysing time or space.
For a sum, empty gives zero and a non-empty list gives head plus the sum of its tail. For a length, empty gives zero and each non-empty level contributes one. The recursive problem size decreases because the tail has one fewer element.
Newly constructed outer lists can still contain shared mutable objects. A pure style needs attention to those elements and to hidden state, not just avoidance of one append call. Use small tests containing empty, one-element and several-element lists to check both structural rules and expected results.
def total(values):
if values == []:
return 0
return values[0] + total(values[1:])
original = [4, 3, 5]
prepended = [9] + original
appended = original + [9]
print(total(original), prepended, appended)
print(original)Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.