Search code examples
pythonfunctionargs

Args with function in Python


I started to learn Python and in exercises about args, I have this block of code, and I don't quite understand why we would define sum as 0 and then i as sum +=

def add(*args):
    sum = 0
    for i in args:
        sum += i
    return sum

Thanks for help!


Solution

  • *args let's you send an undefined amount of arguments as a tuple. At the beginning of the function, where you want to obtain the sum, it's obviously 0 and then you update the value.

    You can also write sum+=i as:

    sum=sum+i
    

    Let's do an small example, you do:

    add(1,2,3)
    

    It would look like:

    1. You enter the function, sum is 0.
    2. You iterate for every element of args (1,2,3).
    Iteration 1: sum=0, i =1, sum=sum+i = 1
    
    Iteration 2: sum=1 (updated last iteration doing 0+1) and i 2, we have sum=sum+i=3
    
    Iteration 3 is 3+3 = 6
    

    Whats the advantage of using *args? Being able to send as many elements as you want without needing to modify the function.