68

I think in Python 3 I'll be able to do:

first, *rest = l

which is exactly what I want, but I'm using 2.6. For now I'm doing:

first = l[0]
rest = l[1:]

This is fine, but I was just wondering if there's something more elegant.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Shawn
  • 1,089
  • 1
  • 7
  • 9

4 Answers4

59
first, rest = l[0], l[1:]

Basically the same, except that it's a oneliner. Tuple assigment rocks.

This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables):

i = iter(l)
first = next(i) # i.next() in older versions
rest = list(i)
NullUserException
  • 83,810
  • 28
  • 209
  • 234
22

You can do

first = l.pop(0)

and then l will be the rest. It modifies your original list, though, so maybe it’s not what you want.

  • 2
    This won't work for empty lists: ```x = []; x.pop(0) Traceback (most recent call last): File "", line 1, in IndexError: pop from empty list ``` – avyfain Jul 19 '17 at 01:01
  • @avyfain: neither would work the Python3 example of the OP. `first, *rest = []` raise a ValueError. – kriss Apr 04 '19 at 12:22
1

Yet another one, working with python 2.7. Just use an intermediate function. Logical as the new behavior mimics what happened for functions parameters passing.

li = [1, 2, 3]
first, rest = (lambda x, *y: (x, y))(*li)
kriss
  • 23,497
  • 17
  • 97
  • 116
0

If l is string typeI would suggest:

first, remainder = l.split(None, maxsplit=1)
Saeed
  • 3,294
  • 5
  • 35
  • 52
fghoussen
  • 393
  • 3
  • 16