Search code examples
tuplespython-2.xiterable-unpacking

Extended tuple unpacking in Python 2


Is it possible to simulate extended tuple unpacking in Python 2?

Specifically, I have a for loop:

for a, b, c in mylist:

which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size four.

I think I will end up using named tuples, but I was wondering if there is an easy way to write:

for a, b, c, *d in mylist:

so that d eats up any extra members.


Solution

  • You could define a wrapper function that converts your list to a four tuple. For example:

    def wrapper(thelist):
        for item in thelist:
            yield(item[0], item[1], item[2], item[3:])
    
    mylist = [(1,2,3,4), (5,6,7,8)]
    
    for a, b, c, d in wrapper(mylist):
        print a, b, c, d
    

    The code prints:

    1 2 3 (4,)
    5 6 7 (8,)