Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Lambda Functions in Python | Functions in Python
Introduction to Python

book
Lambda Functions in Python

All the functions you've created so far are stored in memory after running the code for the first time. However, sometimes you may not want to define a separate function—especially for simple, straightforward tasks. In these cases, Python's lambda function can be useful, as it creates anonymous functions.

python
lambda var1, var2, ... : expression

Let's illustrate this by revisiting our earlier function. You can rewrite it using a lambda function to return the squared sum of two numbers

# Define lambda function
sq = lambda x, y: (x + y)**2
# Test it
print('Sum of 2 and 3 squared is', sq(2, 3))
1234
# Define lambda function sq = lambda x, y: (x + y)**2 # Test it print('Sum of 2 and 3 squared is', sq(2, 3))
copy

Note

Not all functions discussed can be converted into lambda functions. Typically, lambda functions are best suited for concise operations that fit within a single line.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 11

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt