This question already has an answer here:
- Extended tuple unpacking in Python 2 3 answers
In Python 3 I can do the following (see also PEP3132 on Extended Iterable Unpacking):
a, *b = (1, 2, 3)
# a = 1; b = (2, 3)
What can I do to achieve the same similarly elegant in Python 2.x?
I know that I could use single element access and slicing operations, but I wonder if there is a more pythonic way. My code so far:
a, b = (1, 2, 3)[0], (1, 2, 3)[1:]
# a = 1; b = (2, 3)
I found out that the related PEP3132 gives some examples for Python 2.x as well:
Other approaches given in the answers to this question:
Function Argument List Unpacking Approach
requires an extra function definition/call:
I wonder why it is implemented in unpacking function argument lists but not for normal tuple unpacking.
Generator Approach
Credits. Also requires a custom function implementation. Is a little more flexible concerning the number of first variables.
The most pythonic would probably be the ones mentioned in the PEP above, I guess?
I may be wrong but as far as I know
is just syntactic sugar for slicing and indexing tuples. I find it useful but not very explicit.
I've got this handy little function:
For example:
also works with less arguments:
In response to the comment, you can also define:
and use it like this:
Not sure about the context, but what about .pop(0)?
I see that there are tuples in your example, but if you want to do the sort of stuff you do, lists would be more suited, I think? (Unless there is some good reason for them to be immutable not given in the question.)
I don't think there is any better way than the one you posted but here is an alternative using
iter