In Python 3.x, you can do it beautifully:
>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55]
A new feature in 3.x is the use of the * operator when unpacking to indicate any additional values. This is described in PEP 3132 - Advanced Iterative Unpacking . It also has the advantage of working with any repeatable, not just sequences.
It is also really readable.
As described in PEP, if you want to make an equivalent in 2.x (without potentially creating a temporary list), you should do this:
it = iter(iterable) head, tail = next(it), list(it)
Naturally, if you are working with a list, the easiest way without 3.x syntax is:
head, tail = seq[0], seq[1:]
Gareth Latty May 10 '12 at 10:53 2012-05-10 10:53
source share