Search code examples
pythontuplesarguments

Multiplying function with *arg different result when passed (1 , 4 , 3 , 10) and as variable test_1=(1 , 4 , 3 , 10)


I am in early phase of learning python, I am trying *arg functions. I am unable to figure out why below function is reporting different result if same value is passed in different ways. I am using Jupyter notebook. why the value of 2 print in below code is different

## Multiple function using *arg
def multiply_all(*args):
    m = 1
    for i in args:
        m*=i
    return m

## input provided to function in 2 ways

test_1 = (1 , 4 , 3 , 10)
x = multiply_all(test_1)
print(x)
print(multiply_all(1, 4, 3, 10))

I am expecting the result should be same for both print statement


Solution

  • The problem here is that "test_1" only counts as 1 argument as opposed to many since it is a tuple

    Essentially the difference is that when you do print(x) you actually have print(multiply_all((1, 4, 3, 10))) as opposed to what you have below which is print(multiply_all(1, 4, 3, 10)). Notice the difference in the brackets, in the first case you are passing a tuple to the function "(1, 4, 3, 10)" and the program only counts it as a single argument and on the second case you are passing multiple arguments "1, 4, 3, 10"

    You can solve this by simply unpacking the tuple when passing it to the function by putting an asterisk before its name like this:

    ## Multiple function using *arg
    def multiply_all(*args):
      m = 1
      for i in args:
        m*=i
        return m
    
    ## input provided to function in 2 ways
    
    test_1 = (1 , 4 , 3 , 10)
    x = multiply_all(*test_1)
    print(x)
    print(multiply_all(1, 4, 3, 10))
    

    and they should both now equal 120

    You can find more information on this webpage