Search code examples
pythonpython-3.xargumentsiterable-unpacking

Clarifications on Python tuple unpacking


It's understood that unpacking of a tuple can happen only between tuples/list so

x,*y = (1,2,3,4)

is valid. However, if we try to do the unpacking on a single variable

*x = (1,2,3,4,5)

we get an error as x is not a list/tuple hence unpacking cannot occur. If that is the case then how can we use *args to have multiple parameters in function

def max(* args):
  for x in args:
    print(x)

So here if I call max(1,2,3,4). Shouldn't we get an error coz *args is not a tuple therefore we can't do unpacking?


Solution

  • The catch is that the brackets of a parameter list always enclose a tuple. They are brackets you could not omit. So they are not mixed up with operator-priority-brackets

    By the way, fun fact: write (NOTE THE COMMA AFTER THE x)

    *x, = (1,2,3,4,5)
    

    Then it works, just like you would neet to add a comma in a bracket to make it a tuple. like (1) is no tuple, but (1,) is