Question

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

Was it helpful?

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.

OTHER TIPS

In your case, unpack(*(1,2,3)) is just unpack(1, 2, 3).

Implementation of unpack takes the first argument, and an args tale, then returns it as a tuple.

Star syntax is useful, if you would pass arguments as a variable:

a = (1, 2, 3)
first, rest = unpack(*a)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top