2

When I pass 1 argument in args it returns/prints argument and comma in the tuple. But why doesn't add a comma after 2 arguments or more?

def print_args(*args):
    print(args)

#If arguments are more than one or zero:

print_args(1,2,3)  #Out: (1,2,3)
print_args(1,2)    #Out: (1,2)
print_args()       #Out: ()

#If I pass 1 argurment:

print_args(1)      #Out: (1,)  ?
print_args("a")    #Out: ('a',)?
print_args([])     #Out: ([],) ?

#Using return statement instead of print():

def return_args(*args):
    return args

return_args(1,2) #Out: (1, 2)
return_args(1) #Out: (1,)
OrcunSelbasan
  • 144
  • 1
  • 11
  • 1
    Not a strict duplicate, but this is closely related to [What is the syntax rule for having trailing commas in tuple definitions?](https://stackoverflow.com/q/7992559/364696) – ShadowRanger Apr 21 '21 at 02:36

1 Answers1

2

Adding parentheses around a single item is the same as redundant grouping, and does not create the object as a tuple. From the docs:

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

The docs close with commenting that this implementation is indeed, "Ugly, but effective."

spen.smith
  • 576
  • 2
  • 16