Lambda Functions

3 min read ·

A lambda function in Python is a small anonymous function. Anonymous means the function does not have a name.
It is used when you need a short function for a short period of time.

Basic Syntax

A lambda function is written using the lambda keyword.
The expression is executed and returned automatically.
Important

Lambda functions can have multiple arguments but only one expression.

Why Use Lambda Functions?

Lambda functions are useful when You need a short one line function You want cleaner and shorter code You want to pass a function as an argument
They are commonly used with built in functions like map, filter, and sorted.

Lambda vs Normal Function

Normal Function Example

Same Logic Using Lambda

Lambda with One Argument

Lambda with Multiple Arguments

Lambda with Conditional Logic

Lambda with map Function

Lambda with filter Function

Lambda with sorted Function

Real World Scenario

Sorting data based on price, rating, or score is commonly done using lambda functions.

Lambda Inside Another Function

Limitations of Lambda Functions

Lambda functions Cannot contain multiple statements Cannot use loops Cannot use try except
Caution

Use lambda only when logic is simple and readable.

When Not to Use Lambda

Avoid lambda when Logic is complex Debugging is required Function needs reuse
Stop

If readability suffers, replace lambda with a normal function.

Exercise

Create a lambda function that Accepts a number Returns Positive if number is greater than zero Returns Negative if number is less than zero Returns Zero if number is zero