Shawn Shawn - 1 year ago 68
Python Question

Pythonic way to split a list into first and rest?

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.

Answer Source
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) # in older versions
rest = list(i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download