Pythonic way to split a list into first and rest?

PythonListSplitPython 2.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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 3 - Python

If l is string typeI would suggest:

first, remainder = l.split(None, maxsplit=1)

Solution 4 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawnView Question on Stackoverflow
Solution 1 - Pythonuser395760View Answer on Stackoverflow
Solution 2 - PythonOlivier 'Ölbaum' ScherlerView Answer on Stackoverflow
Solution 3 - PythonFGHPView Answer on Stackoverflow
Solution 4 - PythonkrissView Answer on Stackoverflow