Search code examples
pythonpython-3.xtuplesfunction-call

variable positional and printing the values


def minimum (*n):
        print(n)
minimum(1)
minimum(1,2)
    
    
def func(*args):
     print(args)
    
values1 = (1,2)
values2 = ((1,2), (3,4))
func(values1)
func(values2)

OUTPUT:
(1,)
(1, 2)
((1, 2),)
(((1, 2), (3, 4)),)

Process finished with exit code 0

First O/p: I think python is expecting multiple arguments to be passed so there is a comma (,) after 1. ?

Second O/p: Now the python sees multiple arguments being passed there is no comma. It stores the args a tuple?

Third O/p and Fourth O/p: Why is there still a comma? even after I passed 2 tuples assuming that python is expecting multiple tuples like the above?

Help me understand this.


Solution

  • The first output shows a comma because without it, 1 being the only element, (1) would be just a integer (parentheses are wrapping the expression 1), (1,) is shown to differentiate tuples and simple parentheses.

    in the second one, no trailing comma is needed to differentiate tuples, since there are more than one element.

    In the third O/p, you are not passing 1 and 2, but instead you're passing the whole (1,2), so it shows only one item (which is (1,2)) in a tuple, and adds an extra comma. Same for the fourth: your passing the entire ((1,2), (3,4)).