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 =
assignment to split the first three fields from the remaining files.
It looks like this:
>>> r, g, b, *name = line.split() >>> g '73' >>> name ['Radical', 'Red']
We've assigned the first three items to three...