I think in Python 3 I’ll be able to do:
JavaScript
x
2
1
first, *rest = l
2
which is exactly what I want, but I’m using 2.6. For now I’m doing:
JavaScript
1
3
1
first = l[0]
2
rest = l[1:]
3
This is fine, but I was just wondering if there’s something more elegant.
Advertisement
Answer
JavaScript
1
2
1
first, rest = l[0], l[1:]
2
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):
JavaScript
1
4
1
i = iter(l)
2
first = next(i) # i.next() in older versions
3
rest = list(i)
4