10.2 C
New York
Wednesday, November 30, 2022

A Guide to Python Lambda Functions, with Examples – SitePoint

This article introduces Python lambda functions and how write and use them.
Although Python is an object-oriented programming language, lambda functions are handy when you’re doing various kinds of functional programming.
Note: this article will assume you already understand Python programming and how to use a regular function. It’s also assumed you have Python 3.8 or above installed on your device.
In Python, functions can take in one or more positional or keyword arguments, a variable list of arguments, a variable list of keyword arguments, and so on. They can be passed into a higher-order function and returned as output. Regular functions can have several expressions and multiple statements. They also always have a name.
A Python lambda function is simply an anonymous function. It could also be called a nameless function. Normal Python functions are defined by the def keyword. Lambda functions in Python are usually composed of the lambda keyword, any number of arguments, and one expression.
Note: the terms lambda functions, lambda expressions, and lambda forms can be used interchangeably, depending on the programming language or programmer.
Lambda functions are mostly used as one-liners. They’re used very often within higher-order functions like map() and filter(). This is because anonymous functions are passed as arguments to higher-order functions, which is not only done in Python programming.
A lambda function is also very useful for handling list comprehension in Python — with various options for using Python lambda expressions for this purpose.
Lambdas are great when used for conditional rending in UI frameworks like Tkinter, wxPython, Kivy, etc. Although the workings of Python GUI frameworks aren’t covered in this article, some code snippets reveal heavy use of lambda functions to render UI based on a user’s interaction.
Because Python is an object-oriented programming language, everything is an object. Python classes, class instances, modules and functions are all handled as objects.
A function object can be assigned to a variable.
It’s not uncommon to assign variables to regular functions in Python. This behavior can also be applied to lambda functions. This is because they’re function objects, even though they’re nameless:
It’s likely you’ll need to use a lambda function within built-in functions such as filter() and map(),and also with reduce() — which is imported from the functools module in Python, because it’s not a built-in function. By default, higher-order functions are functions that receive other functions as arguments.
As seen in the code examples below, the normal functions can be replaced with lambdas, passed as arguments into any of these higher-order functions:
A common point of confusion amongst developers is differentiating between a statement and an expression in programming.
A statement is any piece of code that does something or performs an action — such as if or while conditions.
An expression is made of a combination of variables, values, and operators and evaluates to a new value.
This distinction is important as we explore the subject of lambda functions in Python. An expression like the one below returns a value:
A statement looks like this:
The Python style guide stipulates that every lambda function must begin with the keyword lambda (unlike normal functions, which begin with the def keyword). The syntax for a lambda function generally goes like this:
Lambda functions can take any number of positional arguments, keyword arguments, or both, followed by a colon and only one expression. There can’t be more than one expression, as it’s syntactically restricted. Let’s examine an example of a lambda expression below:
From the example above, the lambda expression is assigned to the variable add_number. A function call is made by passing arguments, which evaluates to 14.
Let’s take another example below:
As seen above, the lambda function evaluates to 728.0. A combination of positional and keyword arguments are used in the Python lambda function. While using positional arguments, we can’t alter the order outlined in the function definition. However, we can place keyword arguments at any position only after the positional arguments.
Lambda functions are always executed just like immediately invoked function expressions (IIFEs) in JavaScript. This is mostly used with a Python interpreter, as shown in the following example:
The lambda function object is wrapped within parentheses, and another pair of parentheses follows closely with arguments passed. As an IIFE, the expression is evaluated and the function returns a value that’s assigned to the variable.
Python lambda functions can also be executed within a list comprehension. A list comprehension always has an output expression, which is replaced by a lambda function. Here are some examples:
Lambda functions can be used when writing ternary expressions in Python. A ternary expression outputs a result based on a given condition. Check out the examples below:
The concept of higher-order functions is popular in Python, just as in other languages. They are functions that accept other functions as arguments and also return functions as output.
In Python, a higher-order function takes two arguments: a function, and an iterable. The function argument is applied to each item in the iterable object. Since we can pass a function as an argument to a higher-order function, we can equally pass in a lambda function.
Here are some examples of a lambda function used with the map() function:
Here are some lambda functions used with the filter() function:
Here are some lambda functions used with the reduce() function:
Although Python lambdas can significantly reduce the number of lines of code you write, they should be used sparingly and only when necessary. The readability of your code should be prioritized over conciseness. For more readable code, always use a normal function where suited over lambda functions, as recommended by the Python Style Guide.
Lambdas can be very handy with Python ternary expressions, but again, try not to sacrifice readability. Lambda functions really come into their own when higher-order functions are being used.
In summary:
Related content:
Ini is a startup enthusiast, software engineer and technical writer. Flutter and Django are his favorite tools at the moment for building software solutions. He loves Afrobeats music.
© 2000 – 2022 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Related Articles


Please enter your comment!
Please enter your name here

Latest Articles