Python lambdas are so-called anonymous functions with which you can quickly define functions that can have multiple inputs, but only one output. Such anonymous functions are not only used in Python, but also in other programming languages like Java, C#, or C++.
How are normal functions defined in Python?
In Python, the definition of a function is marked with “def”. Then its name is defined and the arguments with names are listed in round brackets. The following function named “sum” simply takes two arguments and adds them together:
The advantage of these functions is that they can be called via a unique name. This helps both to better describe the functionality and to reference the function again at a later time. In addition, the arguments can also have names that help to better understand the result. Another advantage is that explicitly defined functions can also output more than one argument.
Our initial function, for example, can output the difference between the two arguments in addition to the sum:
What are anonymous functions?
However, there is also a second way how functions can be defined in Python. With the help of so-called anonymous functions, these can be defined with just a few lines, usually even just one. These anonymous functions also exist in other programming languages, such as Java or C#. In Python, the argument “lambda” is used for this, which is why anonymous functions in Python are often simply called Python lambdas.
These functions can be easily defined with the parameter “lambda”, the naming of the variables, and the expression that the function should calculate:
This example also clearly shows why Python lambdas are anonymous functions: The function itself cannot be given a name, it can only be stored in a variable (“function”).
So if we want to recreate the sum function from our initial example using Python Lambdas, here’s what it looks like:
As you can see, more than one argument can be passed to Python Lambdas. However, we cannot recreate the function “sum_difference” with Python lambdas, because the anonymous functions can only output one result. So instead, two different functions must be defined and also called twice:
Why should you use Python Lambdas?
There are several cases where it can be useful to use Python lambdas:
- When simple functions are defined that have only one output and a small number of inputs. In large projects it can make sense not to define such a function explicitly, in order to save space and not to cause unnecessary confusion. Furthermore one saves problems with the inheritance, etc. in extensive classes.
- The same argument is also valid if functions are used only once. Then one can do without the explicit definition since anyway nobody must access the function again.
- In addition, anonymous functions can ensure that the content of the function is faster and easier to understand since it is defined in a single line. Explicitly defining functions can result in losing some comprehensibility.
- There are functions in Python, such as “filter” or “map”, that take functions as input. So in these cases, it makes sense to use Python Lambda.
What should you consider concerning scope and closure when using Python Lambdas?
Understanding the scope and closure of Python lambdas is essential to effectively use these anonymous functions. In Python, lambdas follow the same rules of scope and closure as regular (named) functions, but their concise nature can sometimes lead to subtle differences.
Scope of Lambdas:
- Local Scope: Lambdas can access variables from their containing (enclosing) local scope. This means that any variable defined in the same function or block where the lambda is defined can be used inside the lambda.
- Global Scope: Lambdas can access variables from the global scope as well. However, this is not considered a good practice, as it can make the code less readable and maintainable.
Closure of Lambdas:
A closure is a function object that has access to variables in its enclosing lexical scope, even when the enclosing function has finished executing. Lambdas inherently create closures when they reference variables from an enclosing scope.
In the above example, the lambda function lambda_function
“closes over” the variable x
. Even after outer_function
finishing execution, the lambda retains access to the value of x its closure. This is why it can still use x
when called later as lf(5)
.
Cautions:
- Late Binding: Lambdas in Python use late binding for variable values. This means that the values of variables are looked up at the time the lambda is executed, not when it is defined. This can lead to unexpected behavior if the enclosing scope changes between the lambda’s creation and execution.
To avoid late binding issues, you can use default arguments to capture the current value of the variable:
- Encapsulation: While lambdas can access variables from enclosing scopes, it’s generally advisable to use named functions when you need to encapsulate logic or maintainability, especially for complex operations.
Understanding the scope and closure of lambdas is crucial for writing predictable and maintainable code. When used correctly, they provide a powerful way to create concise functions for specific tasks.
How does the filter() function work with Python lambdas?
The function “filter()” can be used to filter a list with a certain condition. The result is a new list that consists only of those elements that meet the condition. Without the explicit function you could also solve this as follows:
The function “filter()” has a total of two inputs, firstly the list to be filtered and secondly the condition to be used for filtering. This filter condition must be a function, which is why Python lambdas are suitable for this:
For such applications, Python Lambdas are of course also an optimal alternative.
What are the best practices to follow when using Python Lamdas?
Python lambda functions are a concise way to create small, anonymous functions, but they should be used judiciously to maintain code readability and maintainability. Here are some best practices and guidelines to follow when working with lambdas:
1. Keep It Simple and Short: Lambdas are intended for small, one-liner functions. Avoid complex logic or multiple expressions within a lambda. If your function becomes too complicated, it’s a sign that you should use a regular named function instead.
2. Use Them with Higher-Order Functions: Lambdas shine when used with higher-order functions like map()
, filter()
, and sorted()
. They are excellent for specifying custom key functions or filtering conditions concisely.
3. Add Descriptive Variable Names: When assigning lambdas to variables or using them as arguments, provide descriptive variable names. This enhances code readability.
4. Be Mindful of PEP 8: Follow Python’s style guide, PEP 8, which suggests using lambdas sparingly. While they are a powerful tool, overuse can make code less readable.
5. Prefer Named Functions for Reusability: For functions that need to be reused in multiple places, opt for named functions with def
. Lambdas are best suited for simple, one-off operations.
6. Avoid Using Lambdas in Complex Expressions: When constructing complex expressions or comprehensions, consider breaking down the problem into smaller, named functions. This enhances code maintainability and debugging.
7. Test and Document: If a lambda serves a critical role in your code, consider adding unit tests and documenting its purpose. This can help other developers understand its intended use.
8. Use Lambdas to Encapsulate Constants: Lambdas can encapsulate constants or default values concisely.
9. Be Aware of Variable Scoping: Remember that lambdas capture variables from their enclosing scope. Be cautious when using them within comprehensions or functions where variable scoping might lead to unexpected behavior.
By following these best practices and guidelines, you can harness the power of Python lambdas while maintaining clean, readable, and maintainable code. Remember that while lambdas can be elegant for simple operations, complex tasks are often better suited to regular named functions. Striking the right balance between conciseness and clarity is key to effective Python Lambdas usage.
This is what you should take with you
- Anonymous functions are used to quickly define functions that do not have to have a name.
- This can be useful if functions are to be used only once or if you want to keep the namespace of variables and functions small.
- In Python, anonymous functions are used with the parameter “lambda”, which is why anonymous functions in Python are also called Python lambdas.
Thanks to Deepnote for sponsoring this article! Deepnote offers me the possibility to embed Python code easily and quickly on this website and also to host the related notebooks in the cloud.
What are Conditional Statements in Python?
Learn how to use conditional statements in Python. Understand if-else, nested if, and elif statements for efficient programming.
What is XOR?
Explore XOR: The Exclusive OR operator's role in logic, encryption, math, AI, and technology.
How can you do Python Exception Handling?
Unlocking the Art of Python Exception Handling: Best Practices, Tips, and Key Differences Between Python 2 and Python 3.
What are Python Modules?
Explore Python modules: understand their role, enhance functionality, and streamline coding in diverse applications.
What are Python Comparison Operators?
Master Python comparison operators for precise logic and decision-making in programming.
What are Python Inputs and Outputs?
Master Python Inputs and Outputs: Explore inputs, outputs, and file handling in Python programming efficiently.
Other Articles on the Topic of Python Lambdas
- w3schools offers even more concrete examples of the use of Python Lambdas.
Niklas Lang
I have been working as a machine learning engineer and software developer since 2020 and am passionate about the world of data, algorithms and software development. In addition to my work in the field, I teach at several German universities, including the IU International University of Applied Sciences and the Baden-Württemberg Cooperative State University, in the fields of data science, mathematics and business analytics.
My goal is to present complex topics such as statistics and machine learning in a way that makes them not only understandable, but also exciting and tangible. I combine practical experience from industry with sound theoretical foundations to prepare my students in the best possible way for the challenges of the data world.