Understanding Lambda Functions in Python

Understanding Lambda Functions in Python

A lambda function is a small anonymous function in Python that can take any number of arguments but can only have one expression. They are commonly used when a short piece of code is required that can be passed as an argument to another function, like map() and filter(). They are also known as "anonymous functions" in some other programming languages.

Here's an example of a lambda function in Python:

Examples

lambda arguments: expression

f = lambda x, y : x + y

print(f(1,1))

output

2

Cube a Number

cube = lambda x: x**3 print(cube(3))

output

27

Find the maximum of two numbers:

maximum = lambda a, b: a if a > b else b print(maximum(2, 3))

output

3

Some useful resources to learn more about lambda functions in Python:

  1. Python documentation on lambda functions: docs.python.org/3/tutorial/controlflow.html..

  2. A Guide to Python's Lambda Function: realpython.com/python-lambda

  3. Python Lambda Function: w3schools.com/python/python_lambda.asp

Until Next Time

Prasad D Wilagama