Lambda function #
In the previous lesson, when we defined a function, those functions would have their own names, which allows us to call the function by its name. For example, the function below has the name say_hello:
def say_hello(name):
print(f"Hello {name}")
However, in some cases, we may want to define a function to be used only once, and creating a named function would take up space in the namespace or the area for naming different things (we cannot use the same name for variables and functions, for example). In this case, we can use the lambda keyword to create a function. The syntax for writing a function using lambda is:
lambda arguments: expression
Functions created with the lambda keyword can accept an unlimited number of arguments but can only have one expression, which will be the statement that returns a value from the function. For example, the following example can be written using either def or lambda, and both functions will work in the same way:
def double(number):
return number * 2
double = lambda number: number * 2
The expression following the : is the statement of the function that will return a value to us, and we can call the function normally, such as:
double = lambda number: number * 2
print(double(10))
We can define functions using the lambda keyword in various ways, such as the examples below:
my_func_0 = lambda: print("Hello there!")
double = lambda number: number * 2
multiply = lambda num1, num2: num1 * num2
test_func = lambda x, y, z: x + y + z
In general, we use lambda functions when we want to create a simple function that performs non-complex tasks. If we want to create a function that performs complex tasks, we can use the def keyword to create a function as usual.
Tests #
- Write a lambda function that returns the input number multiplied by 5 and assign it to the variable
multiply_by_five multiply_by_five(2)should return10multiply_by_five(10)should return50
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules