Question or problem about Python programming:
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 rest = l[1:]
This is fine, but I was just wondering if there’s something more elegant.
How to solve the problem:
first, rest = l, 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)
You can do
first = l.pop(0)
l will be the rest. It modifies your original list, though, so maybe it’s not what you want.
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)
I would suggest:
first, remainder = l.split(None, maxsplit=1)