tags:

views:

94

answers:

2

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.

+2  A: 
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)
delnan
Better is: `first, last = l[:1], l[1:]` in case `l` is empty (and it's prettier ;).
Don O'Donnell
Should mention these are not semantically the same: `l[:1]` is a list, `l[0] ` is an element of the list.
Don O'Donnell
+3  A: 

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.

Ölbaum
Hey! I didn't know you could supply an index to pop. That's unusual, but handy! I was wondering why there's no shift method on lists. Thanks!
Shawn