- Python Snacks
- Posts
- Python Lambda Functions: The Basics, Syntax, and Examples
Python Lambda Functions: The Basics, Syntax, and Examples
See how you can leverage Python’s lambda functions for concise, efficient coding with practical examples.

At some point, you learned about functions along your Python coding journey. Suppose we wanted to do a simple operation such as squaring a number:
def square(number):
return number ** 2
In the above code, we:
Define the function square by using the keyword def
Define a parameter: number
Return the square of the parameter defined in the step above.
While this is a very perfectly valid way of writing code, we can also write it as a lambda function:
square = lambda number: number ** 2
What is a Python lambda function?
A lambda function is a small, anonymous function defined using the lambda keyword.
Unlike regular functions defined with def, a lambda function doesn’t need a name and is typically used for simple, short operations.
Lambda functions can be assigned to a variable, as shown above. They start with the keyword lambda, followed by parameters (in this scenario, number). Then we define what the lambda function does; in this case, squaring a number. A return statement is not needed for lambda functions.
When to use lambda functions (and when not to)
Lambda functions are particularly useful when you need a short function for a short period of time, especially when:
You want to pass a simple function as an argument to higher-order functions like map(), filter(), or sorted() without having to define a separate function.
You need a quick, one-off function that is unlikely to be reused elsewhere in your code.
You want to keep your code concise and readable for small operations that don’t require the complexity of a full function definition.
You want to avoid using lambda functions in scenarios where:
The function’s logic is complex or involves multiple steps.
The logic defined needs to be reused multiple times.
Examples of lambda functions
Inline Callbacks using Flask
In a Flask web application, you might use a lambda to provide a quick, inline function for filtering or mapping data before rendering a template:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
items = [1, 2, 3, 4, 5]
# Use a lambda to double the items before passing to template
doubled_items = map(lambda x: x * 2, items)
return render_template(
'home.html',
items=doubled_items
)
if __name__ == '__main__':
app.run(debug=True)
Doing it this way allows for the code to be more easily readable and to be able to perform operations on the fly rather than having to define a function to carry out the operation.
Configuring Behavior in Machine Learning Pipelines
In a machine learning pipeline, you might use a lambda function to customize the behavior of certain steps without creating separate function definitions:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
# Create a transformer that applies a lambda function
transformer = FunctionTransformer(lambda x: x ** 2)
pipeline = Pipeline([
('square', transformer)
])
X = [[1], [2], [3]]
print(pipeline.fit_transform(X))
# Output: [[1], [4], [9]]
Here, the lambda function lambda x: x ** 2 is used as an example as to how you’d create a custom transformer.
📧Join the Python Snacks Newsletter!🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply