Variadic Functions in Python

Here’s how to implement variadic functions in Python. Variadic functions can be called with any number of extra arguments. For example, the print function is a common variadic function.

Here’s a Python function that will take an arbitrary number of ints as arguments:

def sum(*nums):
    print(nums, " ")
    total = 0
    
    for num in nums:
        total += num
    
    print(total)

if __name__ == "__main__":
    sum(1, 2)
    sum(1, 2, 3)
    
    nums = [1, 2, 3, 4]
    sum(*nums)

To run this code, save it to a file named variadic_functions.py and use the python command to execute it.

$ python variadic_functions.py
(1, 2)  
3
(1, 2, 3)  
6
(1, 2, 3, 4)  
10

Another key aspect of functions in Python is their ability to form closures, which we’ll look at next.