-4

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

Raphael_LK
  • 199
  • 2
  • 13
  • 5
    You are mixing concepts here. The return value of `unpack()` is being unpacked into `first` and `rest` (tuple unpacking). The `unpack()` function signature has a splat-syntax catch-all argument `rest`. And thirdly, you are using a function call feature to expand a sequence into positional arguments. **These are 3 separate things**. – Martijn Pieters Jul 25 '13 at 07:43
  • Yes I understood I was using a function call feature. What I hadn't understood was that unpack(*(1,2,3)) was equivalent to unpack(1,2,3) – Raphael_LK Jul 25 '13 at 07:50

2 Answers2

4

* 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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • This is even clearer than the answer above ! I didn't realise there was a difference between * in a function definition and * in a function call. Thank you ! – Raphael_LK Jul 25 '13 at 07:55
1

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)
Alexander Mihailov
  • 1,154
  • 7
  • 15