Search code examples
pythonpython-2.7iterable-unpacking

Python star unpacking for version 2.7


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?


Solution

  • in python 2.X, you can do:

    c = (1, 2, 3)
    a, b = c[0], c[1:]
    

    as long as c has at least one member it will work because if c only has 1 thing in it c[1:] is [].

    You should probably make sure there is at least one thing in c though, or else c[0] will raise an exception.

    You could do something like:

    try:
        c = tuple(c)
        a, b = c[0], c[1:]
    except TypeError, IndexError:
        # c is not iterable, or c is iterable, but it doesn't have any stuff in it.
        # do something else
        pass