Search code examples
pythonpython-2.7iterable-unpacking

I don't get how tuple unpacking works (Python-2.x)


as I was wondering how tuple unpacking was working, I've found on several threads this answer as an alternative to slicing :

>>>>def unpack(first,*rest):
    return first, rest

which works as follows:

>>>>first,rest=unpack(*(1,2,3))
>>>>first
1
>>>>rest
(2,3)

I don't understand how the * works. The argument "first" isn't supposed to be given to my function unpack ? I thought * meant that the argument was optional.

Thanks for your help


Solution

  • * in a function definition doesn't mean optional; it means "pack any additional (non-keyword) arguments the caller supplied into a tuple and put the tuple here". Similarly, * on a function call means "unpack this sequence of things and supply all the elements as arguments to the function individually."

    unpack(*(1,2,3))
    

    unpacks (1,2,3) and calls

    unpack(1,2,3)
    

    1 is assigned to first, and the remaining arguments 2 and 3 are packed into a tuple and assigned to rest.