Search code examples
pythonsyntaxbackwards-compatibility

How to unpack list into two variables in python2.x


I would like to unpack the return of a function into :

  1. a first variable always set up by the first returned value

  2. a second variable to store any exceeded returned value

To do so, I have this code working under python3.x. How could I make it works with python 2.x (python2.6 at least) ?

a,*b = ['a','b','c']

Edit: This would also work with :

a,*b = ['a']

Solution

  • There is no straight forward way to do this in Python 2.7, instead you can create a new list without the first element and first element alone and unpack them into respective variables.

    data = ['a','b','c']
    a, b = data[0], data[1:]
    print a, b
    

    Output

    a ['b', 'c']
    

    This solution will still work, even if the RHS has only one element

    data = ['a']
    a, b = data[0], data[1:]
    print a, b
    

    Output

    a []