search
HomeBackend DevelopmentPython TutorialA Guide to Python Lambda Functions, with Examples

A Guide to Python Lambda Functions, with Examples

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.

Key Takeaways

  • Python lambda functions are anonymous, usually one-line functions defined using the ‘lambda’ keyword, often used within higher-order functions like map() and filter(). They can handle list comprehension and are useful for conditional rendering in UI frameworks.
  • Lambda functions can take any number of positional arguments, keyword arguments, or both, followed by a colon and only one expression. They are also executed like Immediately Invoked Function Expressions (IIFEs) in JavaScript.
  • Lambda functions can be used within list comprehension and in writing ternary expressions in Python, which output a result based on a given condition. They can also be used within higher-order functions, which are functions that accept other functions as arguments and return functions as output.
  • Although Python lambdas can significantly reduce the number of lines of code, they should be used sparingly and only when necessary. Readability of the code should be prioritized over conciseness. They are not recommended for use when there are multiple expressions, as it can make the code unreadable.

Explaining Python Lambda Functions

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.

Things to Understand before Delving into Python Lambda Functions

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:

<span>def greet(name):
</span>    <span>return <span>f'Hello <span>{name}</span>'</span>
</span>
greetings <span>= greet
</span>greetings<span>('Clint')
</span><span>>>>>
</span>Hello Clint

Higher-order functions like map(), filter(), and reduce()

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:

<span>#map function
</span>names <span>= ['Clint', 'Lisa', 'Asake', 'Ada']
</span>
greet_all <span>= list(map(greet, names))
</span><span>print(greet_all)
</span><span>>>>>
</span><span>['Hello Clint', 'Hello Lisa', 'Hello Asake', 'Hello Ada']</span>
<span>#filter function
</span>numbers <span>= [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
</span><span>def multiples_of_three(x):
</span>        <span>return x % 3 == 0
</span>
<span>print(list(filter(multiples_of_three, numbers)))
</span><span>>>>>
</span><span>[12, 15, 18]</span>
<span>#reduce function
</span>numbers <span>= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</span><span>def add_numbers(x, y):
</span>        <span>return x * y
</span>
<span>print(reduce(add_numbers, numbers))
</span><span>>>>>
</span><span>55</span>

The difference between a statement and an expression

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:

square_of_three <span>= 3 ** 2
</span><span>print(square_of_three)
</span><span>>>>>
</span><span>9</span>

A statement looks like this:

<span>for i in range(len(numbers), 0, -1):
</span>        <span>if i % 2 == 1:
</span>                <span>print(i)
</span>        <span>else:
</span>                <span>print('even')
</span><span>>>>>
</span>even <span>9 even 7 even 5 even 3 even 1</span>

How to Use Python Lambda Functions

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:

<span>lambda arguments : expression</span>

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:

add_number <span>= lambda x, y : x + y
</span><span>print(add_number(10, 4))
</span><span>>>>>
</span><span>14</span>

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:

<span>def greet(name):
</span>    <span>return <span>f'Hello <span>{name}</span>'</span>
</span>
greetings <span>= greet
</span>greetings<span>('Clint')
</span><span>>>>>
</span>Hello Clint

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:

<span>#map function
</span>names <span>= ['Clint', 'Lisa', 'Asake', 'Ada']
</span>
greet_all <span>= list(map(greet, names))
</span><span>print(greet_all)
</span><span>>>>>
</span><span>['Hello Clint', 'Hello Lisa', 'Hello Asake', 'Hello Ada']</span>

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:

<span>#filter function
</span>numbers <span>= [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
</span><span>def multiples_of_three(x):
</span>        <span>return x % 3 == 0
</span>
<span>print(list(filter(multiples_of_three, numbers)))
</span><span>>>>>
</span><span>[12, 15, 18]</span>
<span>#reduce function
</span>numbers <span>= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</span><span>def add_numbers(x, y):
</span>        <span>return x * y
</span>
<span>print(reduce(add_numbers, numbers))
</span><span>>>>>
</span><span>55</span>

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:

square_of_three <span>= 3 ** 2
</span><span>print(square_of_three)
</span><span>>>>>
</span><span>9</span>
<span>for i in range(len(numbers), 0, -1):
</span>        <span>if i % 2 == 1:
</span>                <span>print(i)
</span>        <span>else:
</span>                <span>print('even')
</span><span>>>>>
</span>even <span>9 even 7 even 5 even 3 even 1</span>

Lambda functions within higher-order functions

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:

<span>lambda arguments : expression</span>
add_number <span>= lambda x, y : x + y
</span><span>print(add_number(10, 4))
</span><span>>>>>
</span><span>14</span>

Here are some lambda functions used with the filter() function:

discounted_price <span>= lambda price, discount = 0.1, vat = 0.02 : price * (1 - discount) * (1 + vat)
</span>
<span>print(discounted_price(1000, vat=0.04, discount=0.3))
</span><span>>>>>
</span><span>728.0</span>
<span>print((lambda x, y: x - y)(45, 18))
</span><span>>>>>
</span><span>27</span>

Here are some lambda functions used with the reduce() function:

my_list <span>= [(lambda x: x * 2)(x) for x in range(10) if x % 2 == 0]
</span><span>print(my_list)
</span><span>>>>>
</span><span>[0, 4, 8, 12, 16]</span>
value <span>= [(lambda x: x % 2 and 'odd' or 'even')(x) for x in my_list] 
</span><span>print(value)
</span><span>>>>>
</span><span>['even', 'even', 'even', 'even', 'even']</span>

Conclusion

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:

  • Python lambdas are good for writing one-liner functions.
  • They are also used for IIFEs (immediately invoked function expression).
  • Lambdas shouldn’t be used when there are multiple expressions, as it makes code unreadable.
  • Python is an object-oriented programming language, but lambdas are a good way to explore functional programming in Python.

Related content:

  • Understanding Python Decorators, with Examples
  • Course: Learn Programming Fundamentals with Python
  • Trends in Python: What’s Hot in the Hottest Language Today
  • 5 Common Problems Faced by Python Beginners
  • How Four Programmers Got Their First Python Jobs

FAQs about Python Lambdas

What is a lambda function in Python?

In Python, a lambda function is an anonymous, small, and inline function defined using the lambda keyword. It is often used for short-term operations where a full function definition is unnecessary.

How do I define a lambda function?

The syntax for a lambda function is: lambda arguments: expression. For example: lambda x: x 1 creates a lambda function that adds 1 to its argument.

What is the main difference between lambda functions and regular functions?

Lambda functions are anonymous and are typically used for short, one-time operations. Regular functions are defined using the def keyword and can have multiple expressions and statements.

When should I use a lambda function?

Lambda functions are suitable for short, simple operations, especially when you need a function for a brief period and don’t want to formally define it using def.

Are there any limitations to lambda functions?

Lambda functions are limited in that they can only contain a single expression. They can’t include statements or multiline code.

Can I use lambda functions for complex operations?

While lambda functions are designed for simplicity, they can perform complex operations within the constraints of a single expression. However, for more extended and complex logic, it’s often better to use a regular function.

The above is the detailed content of A Guide to Python Lambda Functions, with Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor