Python Introduction | Functions | Variable-Length Arguments

Another useful argument feature is the variable-length argument. A variable-length argument accepts a variable number of values. In other words, you can pass any number of arguments.

This may seem unusual. How can a function receive an unknown number of arguments? A variable-length argument collects many values in a container. You can think of it as an argument that receives a list-like collection. Instead of creating that collection manually, you pass the values one by one, and Python groups them together automatically.

Define a variable-length argument as follows.

Function Definition 4

def function(*argument):

Add an asterisk (*) before the variable name in the argument definition. Python collects the provided values and passes them through that variable. You can then retrieve and process the values as needed.

Consider the following example.

def calc(*num): 
    total = 0
    for n in num: 
        total += int(n) 
    print('합계 : ' + str(total)) 
    print('평균 : ' + str(total // len(num))) 
   
calc(123, 456, 789, 246, 357, 910) 

The function is defined as calc(*num). All provided arguments are collected in num. You can then iterate over num with a for statement.