Confusion regarding the container type cast on the arguments of a function when using *args

Question:

I have some confusion regarding what container type arguments are cast into when using *args as the input of a function. The python book I’m using for self-study states the following:

You might also want to use the reverse process, where all given positional arguments are packed into a list

This is in reference to using *args as the parameter of a function.

Once I started to play around with this, I tried the following:

def func(*args):
    s=0
    for a in args:
        s += a
    return s, isinstance(args,tuple)

This simply returns the sum of the arguments, and True, meaning the container type is not a list, but rather a tuple.

Am I missing something, or does my book have a typo?

Asked By: William

||

Answers:

That book has a typo. Positional arguments are packed in a tuple. You can check it with this snippet:


def func(*args):
    print(type(args))


func(1,2,3,4)

I find that two reasons might be behind this behavior. First, tuple objects are orders of magnitude (a lot) faster than list objects. This is due in part to the second reason. Second, tuple objects are inmutable, that is, they cannot be modified once they have been created.

Answered By: Luis G.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.