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.
pythonlambda 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
9
1
2
3
4
# 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))
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?
Thanks for your feedback!
Section 6. Chapter 11
Ask AI
Ask anything or try one of the suggested questions to begin our chat