SECTION 10 / 24

Unpack a list into its first element and the rest

1 min read
first([3,13,23,25]) is the element 3. rest gives the list [13,23,25].
first([3,13,23,25]) is the element 3. rest gives the list [13,23,25].
REAL COURSE DATA · BUILD AND UNPACK LISTS

Unpack first, rest, init and last

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

first(L) returns one element. rest(L) returns a list containing all occurrences after the first position. Neither operation means “remove every occurrence equal to the first value”. For [3,3,25], rest is [3,25]. The second 3 remains.

L = [3,13,23,25]
x = first(L)        # x is 3; L is still the original list
R = rest(L)         # R is [13,23,25]
L = rest(L)         # NOW L refers to the shorter list

Keep the difference between evaluating an operation and assigning its result. A local working variable can become shorter while the source data remains available. This lesson’s demonstrations construct result lists rather than mutating the original course dataset.

first([]) has no defined element result. Guard it with a non-empty check. The tutorial defines rest([]) as [] and rest([x]) as []. For a comparison with first(rest(L)), you need at least TWO elements in L, because the rest must also be non-empty.

Try it yourself

What are first([3]) and rest([3])?

Show explained answer

The element 3 and the empty list [], respectively. [3] is not the same value as 3.

Try it yourself

What is rest([3,3,25])?

Show explained answer

[3,25]. Drop one position, not all matching values.

Try it yourself

How many elements are needed before calling first(rest(L))?

Show explained answer

At least two in the original list. A one-element list has an empty rest.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑