As mentioned here, you can use the star for unpacking an unknown number of variables (like in functions), but only in python 3:
>>> a, *b = (1, 2, 3)
>>> b
[2, 3]
>>> a, *b = (1,)
>>> b
[]
In python 2.7, the best I can come up with is (not terrible, but annoying):
c = (1, 2, 3)
a, b = c[0], c[1:] if len(c) > 1 else []
Is there a way to import this from __future__ like division, or will I need my own function to do unknown-length unpacking in python 2.7?
in python 2.X, you can do:
as long as
c
has at least one member it will work because ifc
only has 1 thing in itc[1:]
is[]
.You should probably make sure there is at least one thing in
c
though, or elsec[0]
will raise an exception.You could do something like:
is also an option for handling the case where c is an empty sequence, although it won't distinguish between [None] and [] in terms as assignments to a, b. So use it with care, the try / except is probably best.
I can see no real difference between Python 3 and 2.7 when handling an empty container, but the nice thing about Python 3 here is it works with any iterable.
This works in 2.7 if you know c is a generator.
But the full beauty of unpacking seems to require Python 3.
answer to ex13.py