Introduction
Lambda functions in Python is a feature that allows you to create small, inline functions without the need for a definition using the def
keyword.
Lambda functions, are particularly useful when you need to create simple functions on the fly, for one-time use for tasks such as filtering, mapping, and sorting data.
Because lambda functions are not defined with a name, they are also known as anonymous functions.
Advantages of Lambda Functions
Lambda functions offer several advantages:
- Conciseness: Lambda functions allow you to define simple functionality in a compact and readable manner.
- Inline Usage: You can use lambda functions directly where they are needed, without assigning them a name.
- Functional Programming: Lambda functions facilitate the use of functional programming paradigms like map, filter, and reduce.
- Readability: When the functionality is straightforward, using a lambda function can make the code more self-explanatory.
Limitations of Lambda Functions
While lambda functions are powerful and concise, they are not suited for all scenarios. These are some of their limitations:
- Single Expression: Lambda functions are restricted to a single expression, which limits their complexity.
- No Statements: You cannot include statements (assignments, loops, etc.) inside a lambda function.
- Limited Readability: Due to the previous two limitations, complicated lambda functions can become hard to read, reducing code maintainability.
Lambda Syntax
The basic syntax of a lambda function is as follows:
lambda arguments: expression
Lambda functions consist of three main parts:
- The
lambda
keyword. - A list of arguments separated by commas (similar to function parameters).
- A single expression that is evaluated and returned as the result of the lambda function.
Example:
add = lambda x, y: x + y result = add(3, 5) print(result)
Output:
8
In this example, x
and y
are the lambda function’s arguments, and x + y
is the expression that calculates their sum.
The lambda function is assigned to a variable, add
, and is then executed with the same syntax as for ordinary functions, add(3, 5)
.
Lambda functions, just like regular functions defined with def
, can be assigned to variables, and also passed as arguments to other functions, as you’ll see in the upcoming examples.
More Examples of Using Lambda Functions
Lambda Functions in map
The map
function applies a given function to all items of an iterable (such as a Python list) and returns a new iterable with the results. Lambda functions are often used with map
to create concise code for element-wise operations.
The following example creates a lambda function that squares the number it’s given as an argument. It then uses map
to create an iterable that holds the squares of all the numbers in the original given list, num_lst
. Finally, the iterable is converted to a list and printed.
Example:
num_lst = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, num_lst) print(list(squared))
Output:
[1, 4, 9, 16, 25]
Lambda Functions in filter
The filter
function returns an iterator containing elements from the original iterable that satisfy a given condition. Lambda functions can be used to define these filtering conditions by returning a true expression for items to be kept, and false for items to be filtered out.
The following example creates a lambda function that returns a true expression if an integer is even and a false one if odd. It then uses filter
to create an iterable that holds only the even integers from the original list, num_lst
.
Example:
num_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = filter(lambda x: x % 2 == 0, num_lst) print(list(even_numbers))
Output:
[2, 4, 6, 8, 10]
Lambda Functions in Sorting
Lambda functions are often used to specify custom sorting criteria with the sorted
function.
The following example sorts a list of names alphabetically, but by the last letter of the name instead of the usual first. The lambda function that is given to sorted
, returns the sort criteria, which is the second letter.
Example:
names = ["Alice", "Bob", "Charles"] sorted_names = sorted(names, key=lambda name: name[-1]) print(sorted_names)
Output:
['Bob', 'Alice', 'Charles']
Late Binding of Variables
It’s important to note that the binding of variables in lambda functions is not determined until the lambda function is actually called. This behavior is known as “late binding.” It means that if the value of a variable changes after the lambda function is defined, the lambda function will use the updated value.
In the following example, the lambda function raises its argument, x
, to the power, pow
. pow
is assigned outside of the lambda function. And despite it being 3 when the lambda is defined, the second time the lambda function is called, pow
is 4. Therefore, the argument, 5
, is raised to 4
, giving 625 as the result.
Example:
pow = 3 raise_to_pow = lambda x: x**pow print(raise_to_pow(5)) # Output: 125 pow = 4 print(raise_to_pow(5)) # Output: 625
Output:
125 625
Summary & Reference for Lambda Function
A lambda function in Python is a concise and inline way to create small functions for specific tasks without using the traditional def
keyword for function definition.
Lambda functions are also known as anonymous functions because they are not defined with a name.
The syntax of a lambda function consists of the lambda
keyword, a list of arguments, and a single expression.
lambda arguments: expression
add = lambda x, y: x + y result = add(3, 5) print(result)
Lambda functions can be assigned to variables, passed as arguments to other functions, and used just like regular functions.
Late binding of variables in lambda functions means that their behavior can change based on the value of variables at the time of execution.