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)
Author by
Shawn
Updated on July 08, 2022Comments
-
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 almost 8 years
list
does not have a.split()
method. -
fghoussen almost 8 yearsooops ! my mistake, though it was for a string
-
avyfain almost 7 yearsThis 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 about 5 years@avyfain: neither would work the Python3 example of the OP.
first, *rest = []
raise a ValueError. -
Gnudiff almost 5 yearsStill +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 almost 3 yearsNote this throws an error if the split only returns a list of 1 item