python

[Python] Function parameters - pack and unpack

# Asterisk turns parameter into tuple reference
def average(*nums):
    result = sum(nums)/len(nums)
    return result

# Example 1
x = average(10,20,30)
print('Example 1(pack): ',x)

# Example 2
x = average(10,20,30,40,50)
print('Example 2(pack): ', x)

# Asterisk unpacks tuple before sending to the function
# Example 3
mytuple = (10,20,30)
x = average(*mytuple)
print('Example 3(unpack): ', x)

Example 1(pack):  20.0

Example 2(pack):  30.0

Example 3(unpack):  20.0

Was this helpful?