How to use variable length parameters

Create a function with variable length parameters

The variable length function parameters allow us to create a function which can accept any number of parameters.


def print_params(*params): 
    print params 
# from   ww  w .  j  av a2 s .  c o  m
print_params('Testing') 
print_params(1, 2, 3) 

The code above generates the following result.

The star in front of the parameter puts all the values into the same tuple.

We can mix variable length parameter with other type of parameter.


def print_params_2(title, *params): 
    print title # ww w. ja v a  2  s .  c  o m
    print params 

print_params_2('Params:', 1, 2, 3) 
print_params_2('Nothing:') 

The code above generates the following result.

** is for variable named parameters.


def print_params_3(**params): 
    print params 

print_params_3(x=1, y=2, z=3) 

The code above generates the following result.

Combine everything together


def print_params_4(x, y, z=3, *pospar, **keypar): 
    print x, y, z 
    print pospar 
    print keypar 
# from ww  w. j  a va 2  s.com
print_params_4(1, 2, 3, 5, 6, 7, foo=1, bar=2) 
print_params_4(1, 2) 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules