Grab Head, Tail and Middle with Star-Unpacking

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
Implement first_middle_last(sequence) using extended unpacking (first, *middle, last = sequence) to return a tuple (first, middle, last), where middle is a list of everything between the first and last elements. Handle a sequence of exactly length 2 (middle is an empty list), and raise ValueError for sequences shorter than 2 elements with an explicit guard clause rather than letting the raw unpacking fail with an unclear error.

Examples

Example 1
Input
first_middle_last([1, 2, 3, 4, 5])
Output
(1, [2, 3, 4], 5)
Explanation

first=1, last=5, everything else collected into middle.

Example 2
Input
first_middle_last([1, 2])
Output
(1, [], 2)
Explanation

No elements are left over for middle.

Example 3
Input
first_middle_last([1])
Output
ValueError raised
Explanation

Guard clause rejects sequences shorter than 2 elements.

Constraints

  • Must raise ValueError explicitly for len(sequence) < 2, before attempting the unpack.

Topics

TuplesUnpacking

Companies

MetaAirbnb

Hints

Hint 1

Check len(sequence) < 2 first and raise ValueError.

Hint 2

first, *middle, last = sequence collects the interior into a list automatically.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.