Head and tail in line

Is there a python way to unpack the list in the first element and the tail in one 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] 
+80
python list head tail
May 10 '12 at 10:52
source share
5 answers

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:] 
+168
May 10 '12 at 10:53
source share
 >>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> head, tail = mylist[0], mylist[1:] >>> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] 
+35
May 10 '12 at 10:54
source share

For the O (1) complexity of the head,tail operation head,tail you must use deque .

In the following way:

 from collections import deque l = deque([1,2,3,4,5,6,7,8,9]) head, tail = l.popleft(), l 

This is useful when you have to iterate through all the elements of a list. For example, in a naive union of 2 sections in a merge sort.

+8
Oct 03 '16 at 18:21
source share

Python 2 using lambda

 >>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) >>> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] 
+2
Jul 13 '16 at 19:31
source share

Based on @GarethLatty's Python 2 solution , the following is a way to get a single-line equivalent without intermediate variables in Python 2.

 t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0] 

If you want it to be protected from exceptions (i.e. it supports an empty list), add:

 t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0] 

If you want to do this without a semicolon, use:

 h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0] 
+1
Jul 30 '18 at 17:18
source share



All Articles