Python:Function
lastmod 2020-10-17created 2015-04-149 edits
Python functools package.
Built-in Functions
filter
Feeds the elements of the iterable given as the second argument one by one into the function given as the first argument, and returns only those whose return value is true.
reduce
| WARNING |
| Removed from the built-in functions as of python3. It is available from the |
Example:
args and kwargs
- Python - What do * and ** before a parameter mean? (*args, **kwargs)
- Stackoverflow: *args and **kwargs?
*args is used when you don't know how many parameters will be received. They are passed as a tuple. **kwargs lets you send parameter names along with the values. They are passed as a dictionary.
def print_param3(*args, **kwargs):
print args
print kwargs
print_param3('a', 'b')
#('a', 'b')
#{}
print_param3(third = 'c', fourth = 'd')
#()
#{'fourth': 'd', 'third': 'c'}
print_param3('a', 'b', third = 'c', fourth = 'd')
#('a', 'b')
#{'fourth': 'd', 'third': 'c'}
Passing variable arguments as a Tuple
def test_var_args(farg, *args):
print "formal arg:", farg
for arg in args:
print "another arg:", arg
test_var_args(1, "two", 3)
Passing variable arguments as a Dictionary
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
test_var_kwargs(farg=1, myarg2="two", myarg3=3)
Using variable arguments and dictionaries together
Order of *arg, **kwargs, and formal arguments (format args):
Variable argument By-pass
To pass variable arguments on again, write them in the arguments with * or **.
See also
Favorite site
- Python lecture part 7. Functions
- Functions 1 (declaration, return types, argument passing & modes, scoping rules)
Variable argument
- Python variable arguments and lambda functions
- Things experienced Python users should know (lambdas, variable arguments, decorators)
- Variable numbers of arguments in Python functions
- How to use *args and **kwargs in Python
Pages that link here