Is there a pythonic way to unpack a list in the first element and the “tail” in a single command?
For example:
>> head, tail = **some_magic applied to** [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Under Python 3.x, you can do this nicely:
A new feature in 3.x is to use the
*operator in unpacking, to mean any extra values. It is described in PEP 3132 – Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.It’s also really readable.
As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:
As noted in the comments, this also provides an opportunity to get a default value for
headrather than throwing an exception. If you want this behaviour,next()takes an optional second argument with a default value, sonext(it, None)would give youNoneif there was no head element.Naturally, if you are working on a list, the easiest way without the 3.x syntax is: