pythonpython-3.xfunction-signaturepositional-argument

Is *args guaranteed to preserve order?


In Python3 i can use * to accept any number of positional arguments.

A sample demonstrating this:

def a(*args):
    for argument in args:
        print(argument)
a(1,2,3,4)

Would thus print:

1
2
3
4

What I'm uncertain is, if the order of positional arguments stored in args is actually guaranteed to be preserved?

Can I trust that if I call a(1,2,3,4) then args is always (1,2,3,4) or is this just a side effect of an implementation detail?


While trying to look into this, I saw that order in **kwargs is preserved since Python 3.6 and this is specified in PEP-468 how ever I didn't find any mention of *args in this regard.


Solution

  • Yes. This is because *args is in the format of a tuple, which preserves order. Dictionaries and lists preserve order as well, sets are one of the few integrated data types which do not.