Using the head, *tail assignment

When working with sequences, there are some algorithms which work by separating the head of the sequence from the rest of the sequence. We can do this with a variation on the assignment statement. We like to call this the head, *tail = assignment statement.

Let's say that we have an input string with a list of values, something like this:

>>> line = "255  73 108 Radical Red"
>>> line.split()
['255', '73', '108', 'Radical', 'Red']

We have split the string into space-delimited words with line.split(). In this case, the head of the list is the first three fields of the red, green, and blue elements of a color. The tail is all the remaining fields, which is the name parsed into separate words.

We can use head, *tail =

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.