Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading