Search
Functions: Argument Types and Lambda Functions

Positional arguments

Python functions are defined with the def keyword. They take arguments and optionally return a Python object of any type, i.e. list, integer, etc. For example, we can define our own sum function as follows, in this case we will return the addition of two values a and b

In this example, a and b are said to be positional arguments. They must appear in exactly the order they are the defined and they cannot be omitted.

def sum(a, b):
    return a + b

Calling our function with a=1 and b=2 returns the expected answer 3.

sum(1,2)
3

Likewise with a=2 and b=2

sum(2,2)
4

Keyword arguments

Keyword arguments are defined by assigning a value to the argument, e.g. b=2 in this example. Keyword arguments are optional when calling the function and if not defined, automatically take on the default value that was assigned in the function definition.

def sum(a, b=2):
    return a + b

Here are a couple of examples where we don't specify b and it takes on the default value, i.e. b=2

print(sum(2))
print(sum(4))
4
6

The default value can always be overwritten.

sum(2, b=3)
5

Variable positional arguments

Functions can have a variable number of arguments, this is specified in the function definition with a * in front of the variable name. In this example we define a function that sums all the arguments, no matter how many are given.

Specificially, *var_args is a variable positional argument.

def sum(*var_args):
    
    ans = 0
    for i in var_args:
        ans += i
        
    return ans

We can now call the function with any number of arguments and they will be summed accordingly.

sum(1,2)
3
sum(1,2,3,4)
10
sum(1,2,3,4,100)
110

Variable keyword arguments

We can also have variable keyword arguments. These utilize the special syntax of **kwargs. The keyword arguments are passed into the function as a Python dictionary. For example, a function with the signature:

a_keyword_arg_function(**kwargs)

That is called with

a_keyword_arg_function(a=1, b=2, c='three')

will have a variable available for use inside the function

kwargs = {'a': 1, 'b': 2, 'c'='three'}

Let's show an example in code:

def keyword_arg_function(**kwargs):
    
    for key, value in kwargs.items():
        print('keyword: {} with value = {}'.format(key, value))
        
keyword_arg_function(name1='Romeo', name2='Juliet')
keyword: name1 with value = Romeo
keyword: name2 with value = Juliet

Lambda functions

Another way to quickly define functions is with the use of the lambda keyword. This are called lambda functions`or anonymous functions in other languages.

f = lambda x: x + 2

The function can then be called like any normal function.

f(2)
4

Lambda functions can have more than one variable and can also have keyword arguements as well.

g = lambda x, y=2:  x + y
print(g(2))
print(g(2,2))
4
4

Further Reading

Further reading on functions can by found in the Python documentation.