Pythonic way to split a list into first and rest?

34,944

Solution 1

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.

Solution 2

If l is string typeI would suggest:

first, remainder = l.split(None, maxsplit=1)
Share:
34,944
Shawn
Author by

Shawn

Updated on July 08, 2022

Comments

  • Shawn
    Shawn almost 2 years

    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.

  • Uyghur Lives Matter
    Uyghur Lives Matter almost 8 years
    list does not have a .split() method.
  • fghoussen
    fghoussen almost 8 years
    ooops ! my mistake, though it was for a string
  • avyfain
    avyfain almost 7 years
    This won't work for empty lists: x = []; x.pop(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop from empty list
  • kriss
    kriss about 5 years
    @avyfain: neither would work the Python3 example of the OP. first, *rest = [] raise a ValueError.
  • Gnudiff
    Gnudiff almost 5 years
    Still +1 for while it is wrong in this case, it was a good thing, because I wanted to split string and assign head + rest of result to different variables.
  • Peter Gibson
    Peter Gibson almost 3 years
    Note this throws an error if the split only returns a list of 1 item