How to Pass Dynamic Values to a Function in Python

How to Pass Dynamic Values to a Function in Python

ยท

1 min read

An array or list of values is called dynamic when its size is not decided i.e the number of elements is not known. What if we want to pass this dynamic array to a function where we want to perform some operations on it?

We can pass all the values to a function which is then converted as a list using an asterisk (*).

*args is used to pass a variable-length argument to a function. It is used when we are unsure about the number of arguments passed to a function.

It is not necessary to name the argument as args . Here, in the below example, it is arguments . Its type is tuple .

# find total sum 
def totalSum(*arguments):
    sum = 0
    for num in arguments:
        sum += num
    print(sum)

# passing dynamic values
totalSum(4, 5, 1, 10)
# Output-> 20
totalSum(1, 2)
# Output-> 3
ย