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?
Similar Posts
- Function argument unpacking in Python
- [Python] Range - standard function to create a list of numbers
- [Python] Function returns multiple values
- [Python] Eval() function
- [Python] Get nodeid, module, function name using Pytest request built-in fixture
- [Python] Default value of function argument
- [Python] Using inspect.stack() to get module name, path, function name