Search code examples
pythonpython-3.xtuplespython-internals

tuples as function arguments


a tuple in python (in a code block) is defined by the commas; the parentheses are not mandatory (in the cases below). so these three are all equivalent:

a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2

if i define a function

def f(a, b):
    print(a, b)

calling it this way will work:

f(2, 3)

this will not:

f((2, 3))
# TypeError: f() missing 1 required positional argument: 'b'

how does python treat tuples differently when they are function arguments? here the parentheses are necessary (i understand why this is the case and i am happy python works this way!).

my question is: how does python treat tuples differently when they are function arguments.


Solution

  • For convenience, Python constructs a temporary tuple as needed for an assignment statement. Thus, all three of your assignment statements are exactly the same once they reach data movement.

    A function call is not an assignment statement; it's a reference mapping. Therefore, the semantics are different.

    If you want Python to unpack your tuple into two separate arguments, use the * operator:

    f(*(2, 3))