7 min to read
Python - Writing functions - More on arguments and lambda functions
This article is a part of the Python - 101 series, you can access the full version of the series here:
-
Coding 101
-
Writing functions in Python
- Basic
- Scope of variables
- More on arguments and lambda functions (you are here!)
- Best practices
-
Control flows in Python
-
Errors and exceptions
-
Classes
Welcome to the fifth article of the Python - Coding 101 series, after reading this article, you’ll learn:
- Different types of arguments
- How to create a default arguments, variable-length arguments
- How and when to use lambda functions
In the last article, you have known how to write function, know what scope is and how to call variable from a specific scope. In this article, we will discuss about different types of arguments in Python function, and how to write a function even faster using lambda function.
The outline of the post is as follow:
1. Function arguments
1.1. Review
Before starting reading this article, I expect you to know what arguments is in a functions? What is the difference between arguments and parameters? If you forgot, please refer to this article in the 101 series.
To sum up, the term parameter refers to any declaration within the parentheses following the function name in a function declaration or definition; whereas the term argument refers to any expression within the parentheses of a function call.
In Python, It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined: default arguments, keyword arguments and arbitrary argument lists.
1.2. Default arguments
Consider this example:
def bark(sound, times):
print(str(sound) * times)
We have just declared a function, which takes a string and replicates it. If we call the function with the following argument bark(sound='woof', times=2)
then woofwoof
will be printed to the screen. However, what if we call the function bark()
with only one argument, for instance, bark(sound='woof')
?
In such case, Python will not understand which value does times
in the print()
statement take, thus return an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 bark('woof')
TypeError: bark() missing 1 required positional argument: 'times'
So in order to call bark(sound='woof')
successfully, Python need to know what value does times
take right? What when we want to use default argument. Declaring a function with default arguments lets Python know what value that parameter would take in case we do not give it any value.
To define a default argument, you need to use the assignment statement in the function declaration statement. For example:
def bark(sound, times=2):
print(str(sound) * times)
This will allow bark(sound='woof')
to run successfully, because Python has already know times
would take the value of 2.
Notice: your function declaration/call would fail if non-default argument follows default argument.
1.3. Keyword arguments
Function in Python can also be declared with keyword arguments (**kwargs
). What makes **kwargs
different is that it allows you to pass a variable number of keyword arguments to functions.
To understand this idea better, you’re going to use **kwargs
in this exercise to define a function that accepts a variable number of keyword arguments.
def report(**kwargs):
print("\nBEGIN: REPORT\n")
# Iterate over the key-value pairs of kwargs
for item in kwargs:
# Print out the keys and values, separated by a colon ':'
print(item + ": " + kwargs[item])
print("\nEND REPORT")
kwargs
comes in the form of a dictionary, which consists of key, value pairs. So if we want to access the elements inside, you need a for loop.
Using **kwargs
, you don’t need to specify every arguments passed in the function call in the function declaration. You can pass ten, hundreds or even thousands of arguments into your function call using **kwargs
.
report(username='hieutm', name='hieu tran', role='data analyst')
print('-' * 50)
report(name='tran minh hieu', alias='hiu tran', university='foreign trade university')
Notice: you must declare **kwargs after normal argument.
1.4. Arbitrary argument lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple, where as kwargs
are wrapped up in a dictionary.
def concat(*args):
output=''
for words in args:
output = output + words
print(output)
concat('yes!','you did it')
Output:
yesyou did it
Notice: you can use other parameters both before and after the *args
. However, when these parameters are placed before the *args
, you can call it by using both positional & keyword arguments
. But if it is the other way round, they can only be used as keywords.
2. Lambda function
Some function definitions are simple enough that they don’t need to be declared by def
. In such case, you can refer to lambda function. Lambda function is a small anonymous function. A lambda functioncan take any number of arguments, but can only have one expression.
A lambda function in Python can be made using the lambda
expression. I.e:
lambda <param1>, <param2>, <param3>: <expression>
For example, you can create the function bark
using lambda function as follow:
# normal function
def bark(sound, times=2):
print(str(sound) * times)
# lambda function
bark = lambda x,y: print(str(x) * y)
By doing this, you write less lines of code, which is pretty awesome and will come in handy, especially when you’re writing and maintaining big programs. Lambda function can also be used in a return
function or as an argument. For example:
# this function return another function
def make_incrementor(n):
return lambda x: x + n
# we use lambda function as an argument in this example
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
3. Exercises
- Write a Python function that takes a list and returns a new list with unique elements of the first list
-
Write a function that draws a grid like the following
- Write a function that draws a similar grid with four rows and four columns.
Comments