Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In standard Python programming, functions are declared with the def keyword, given an explicit name, and stored permanently in memory for reuse across an application.
However, programmers frequently encounter situations where a function is needed only once, for a fleeting instant—such as transforming numbers in a pipeline or custom-sorting a list of dictionaries. For these throwaway, single-expression utilities, Python provides lambda functions (also known as anonymous functions).
+-------------------------------------------------------------------------------+
| LAMBDA FUNCTION REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------------+
1. THE STANDARD `def` FUNCTION (Engraved Ceramic Mug):
- Designed with care, washed, placed in the kitchen cabinet, and reused
every morning for years.
- Has an official permanent name and location.
- Suited for substantial, multi-step business logic.
2. THE ANONYMOUS `lambda` (Disposable Earthen Kulhad / Paper Cup):
- Picked up at a railway platform stall for a quick 2-minute sip of chai.
- Once consumed, it is discarded immediately.
- Has no permanent name engraved on it.
- Perfect for a single-expression task right where you need it.
+-------------------------------------------------------------------------------+def vs. lambdaLet us contrast a traditional function with its inline lambda equivalent:
Output:
calc_gst = lambda .... If you need to name a function, write a proper def compute_gst(...):. Lambdas should be used primarily as inline, anonymous arguments passed into higher-order functions!sorted() and .sort()The primary real-world use case for lambda functions is providing custom sort keys to the sorted() built-in or list.sort() method:
Output:
Notice how lambda c: c["population_lakhs"] cleanly instructs Python to extract the specific dictionary key for numerical comparison.
map() and filter()Python provides built-in functional primitives that accept a function as an argument:
Output:
map() and filter() with lambdas because they are more readable:
- [c * 9/5 + 32 for c in temps] (preferred over map)
- [c for c in temps if c > 30] (preferred over filter)While lambdas cannot contain multi-line if-elif-else statements, they can contain single-line ternary expressions:
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO use lambdas for short, single-line sorting keys (e.g. key=lambda x: x[1]). | DON'T write multi-line logic or complex arithmetic inside lambdas. |
DO prefer def when assigning a function to a variable name (PEP 8 compliance). | DON'T write f = lambda x: ... when a standard def f(x): is clearer. |
DO prefer list comprehensions over map(lambda ...) and filter(lambda ...). | DON'T use the return keyword inside a lambda (SyntaxError: 'return' outside function). |
lambda args: expression.def keyword or require a function name.return keyword is prohibited; the single expression is evaluated and returned implicitly.sorted(), min(), and max().map() and filter() with lambdas for everyday sequence transformations.return StatementIf a function computes a value but doesn't return it, Python returns None by default:
global KeywordReading a global variable is permitted, but assigning to it creates a local variable unless explicitly declared:
x and y?A. def lambda(x, y): return x * y B. lambda x, y -> x * y C. lambda x, y: x * y D. (x, y) => x * y
return keyword inside a lambda function (e.g. lambda x: return x * 2)?A. The lambda runs normally B. It raises a SyntaxError C. It returns None D. It prints the result to the console
students = [("Amit", 85), ("Pooja", 92), ("Rohan", 78)]. How can you sort them in descending order of marks?A. students.sort(key=lambda s: s[1], reverse=True) B. students.sort(descending=True) C. sorted(students, by="marks") D. students.sort(key=s[1])
square = lambda x: x**2?A. It is the recommended style for math functions B. It is discouraged; a standard def square(x): return x**2 should be used instead C. It is required for high performance in Python 3.12 D. It emits a deprecation warning
A. Exactly one expression B. Up to three expressions separated by semicolons C. Any number of expressions inside curly braces D. As many lines as indented properly
Build an automated financial stock analytics and sorting utility for an Indian brokerage platform (Zerodha Kite / Groww).
The portfolio database stores equity holdings as dictionaries with the following schema:
ticker: Stock trading symbol (e.g. "RELIANCE", "TCS", "INFY").current_price_inr: Current market price per share.shares_held: Number of shares in investor portfolio.day_change_pct: Daily price percentage fluctuation (positive or negative float).pe_ratio: Price-to-Earnings valuation ratio.current_price_inr * shares_held).sorted() with lambda keys to generate three distinct analytical views:day_change_pct (Descending).pe_ratio (Ascending - lowest P/E first).In the next lesson, we will continue your Python learning journey with Recursion (14: Functions).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Return Values | Recursion |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.