PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Lambda Functions: Anonymous One-Line Functions in Python (लैम्ब्डा फंक्शन्स (Lambda): अनाम एक-पंक्ति फंक्शन्स का सिंटैक्स) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: A lambda function in Python is a small, anonymous single-expression function created inline via `lambda parameters: expression` without using `def`. It evaluates its single expression and returns the result implicitly, making it ideal for short throwaway callbacks in sorting, mapping, and filtering.
अध्याय सार: पायथन में लैम्ब्डा (lambda) फंक्शन `def` के बिना `lambda parameters: expression` सिंटैक्स से बनाया जाने वाला एक छोटा, अनाम (anonymous) एक-पंक्ति फंक्शन है। यह अपने एकमात्र एक्सप्रेशन का मूल्यांकन कर स्वतः परिणाम लौटाता है, जिससे यह sorting, map और filter जैसे कॉलबैक कार्यों के लिए उपयुक्त बनता है।
Lambda Functions: Anonymous One-Line Functions in Python: Detailed Notes & Architecture (लैम्ब्डा फंक्शन्स (Lambda): अनाम एक-पंक्ति फंक्शन्स का सिंटैक्स)
1. Lambda Syntax, Single-Expression Limit, and Implicit Return (लैम्ब्डा सिंटैक्स, एकल-एक्सप्रेशन सीमा और स्वतः रिटर्न)
[EN] The general syntax `lambda arg1, arg2: expression` constructs a full Python `function` object (`types.FunctionType`) whose `__name__` attribute is `'<lambda>'`. Unlike `def` blocks, a lambda body is strictly limited to a single Python expression—statements such as `return`, `pass`, `raise`, `try`, `for`/`while` loops, and assignment (`x = 1`) raise `SyntaxError`. Writing `return` inside a lambda is both redundant and illegal because lambda automatically evaluates and returns its single expression's value. However, expression-level constructs like ternary conditionals (`'even' if x % 2 == 0 else 'odd'`), comprehensions, and the Python 3.8+ walrus operator (`:=`) are valid inside a lambda body.
[HI] `lambda arg1, arg2: expression` सिंटैक्स से एक वास्तविक पायथन `function` ऑब्जेक्ट बनता है जिसका `__name__` एट्रिब्यूट `'<lambda>'` होता है। `def` के विपरीत, लैम्ब्डा बॉडी में केवल एक ही एक्सप्रेशन लिखा जा सकता है; `return`, `pass`, `raise`, `for`/`while` लूप या असाइनमेंट (`x = 1`) जैसे स्टेटमेंट लिखने पर `SyntaxError` आता है। लैम्ब्डा अपने एकमात्र एक्सप्रेशन का मान स्वतः लौटाता है, इसलिए इसके अंदर `return` कीवर्ड लिखना अवैध है। यद्यपि टर्नरी कंडीशनल (`'even' if x % 2 == 0 else 'odd'`), लिस्ट कॉम्प्रिहेंशन और वालरस ऑपरेटर (`:=`) जैसे एक्सप्रेशन वैध हैं।
2. Supported Parameter Forms in Lambda Expressions (लैम्ब्डा में समर्थित पैरामीटर रूप)
[EN] Despite its compact one-line appearance, a lambda parameter list supports virtually every parameter feature available to `def` functions. You can write zero-argument lambdas (`lambda: 42`), multiple parameters (`lambda x, y: x + y`), default values (`lambda x, y=10: x * y`), and variadic forms (`lambda *args, **kwargs: len(args)`). Even positional-only `/` and keyword-only `*` markers work inside lambdas, as in `lambda x, /, *, scale=1: x * scale`. The only difference in header metadata is that lambda parameters cannot carry PEP 3107 type annotations (`lambda x: int: x` triggers SyntaxError because `:` terminates the header).
[HI] संक्षिप्त एक-पंक्ति रूप के बावजूद, लैम्ब्डा पैरामीटर सूची लगभग वे सभी सुविधाएँ स्वीकार करती है जो `def` में उपलब्ध हैं। इसमें शून्य-आर्गुमेंट (`lambda: 42`), एकाधिक पैरामीटर (`lambda x, y: x + y`), डिफ़ॉल्ट मान (`lambda x, y=10: x * y`), और `*args, **kwargs` सब चलते हैं। यहाँ तक कि पोजिशनल-ओनली `/` और कीवर्ड-ओनली `*` भी लैम्ब्डा में मान्य हैं, जैसे `lambda x, /, *, scale=1: x * scale`। केवल टाइप एनोटेशन (`x: int`) लैम्ब्डा हेडर में नहीं लिखे जा सकते क्योंकि पहला कोलन `:` पैरामीटर सूची को समाप्त कर देता है।
3. Idiomatic Use Cases and PEP 8 Guidelines (आदर्श उपयोग और PEP 8 दिशानिर्देश)
[EN] Lambda functions shine as inline key selectors or short predicates passed directly to higher-order functions like `sorted()`, `min()`, `max()`, `map()`, and `filter()`. For instance, sorting `(name, score)` tuples by descending score takes a single readable line: `sorted(students, key=lambda s: s[1], reverse=True)`. PEP 8 (rule E731) explicitly advises against binding a lambda to a variable (`square = lambda x: x * x`), recommending `def square(x): return x * x` instead. Using `def` for named functions gives meaningful `__name__` strings in stack tracebacks, supports docstrings, and allows multi-step debugging.
[HI] लैम्ब्डा का सर्वश्रेष्ठ उपयोग `sorted()`, `min()`, `max()`, `map()` और `filter()` जैसे हायर-ऑर्डर फंक्शन्स में छोटे इनलाइन कॉलबैक या `key` फंक्शन देने में होता है। उदाहरण के लिए `(name, score)` टपल्स को स्कोर के अनुसार सॉर्ट करने के लिए `sorted(students, key=lambda s: s[1], reverse=True)` बहुत स्वच्छ तरीका है। हालाँकि, PEP 8 (नियम E731) किसी लैम्ब्डा को नाम वाले वेरिएबल में सहेजने (`square = lambda x: x*x`) से मना करता है और इसके स्थान पर `def` लिखने की सलाह देता है। `def` से बने नामित फंक्शन एरर ट्रेसबैक में स्पष्ट नाम दिखाते हैं और डॉकस्ट्रिंग भी रखते हैं।
4. IIFE Usage and the Late-Binding Closure Pitfall (तत्काल कॉल (IIFE) और लेट-बाइंडिंग क्लोज़र ट्रैप)
[EN] A lambda can be defined and immediately invoked in place (IIFE): `(lambda x, y: x + y)(3, 4)` evaluates directly to `7`. When creating lambdas inside a loop—such as `funcs = [lambda: i for i in range(3)]`—developers often fall into Python's late-binding closure trap. Because closures look up free variable `i` when called rather than when defined, all three lambdas return `2` (the final loop value of `i`). Binding the current loop value as a default parameter (`[lambda i=i: i for i in range(3)]`) captures each iteration's value eagerly so calling them produces `0, 1, 2`.
[HI] लैम्ब्डा को परिभाषित करते ही तुरंत कॉल (IIFE) भी किया जा सकता है: `(lambda x, y: x + y)(3, 4)` का मान तुरंत `7` मिलता है। लूप के अंदर लैम्ब्डा बनाते समय (`funcs = [lambda: i for i in range(3)]`) डेवलपर्स अक्सर 'लेट-बाइंडिंग क्लोज़र ट्रैप' में फँस जाते हैं। चूँकि क्लोज़र में `i` का मान परिभाषा के समय नहीं बल्कि कॉल के समय पढ़ा जाता है, इसलिए तीनों लैम्ब्डा अंततः `i` का अंतिम मान `2` ही लौटाते हैं। इसे ठीक करने के लिए डिफ़ॉल्ट पैरामीटर `[lambda i=i: i for i in range(3)]` लिखा जाता है, जिससे हर चक्र का मान `0, 1, 2` तुरंत लॉक हो जाता है।
Syntax, Formula & Technical Example (Lambda Functions: Anonymous One-Line Functions in Python)
pairs = [("Ravi", 82), ("Anu", 95), ("Dev", 78)]
ranked = sorted(pairs, key=lambda p: p[1], reverse=True)
print(ranked) # [('Anu', 95), ('Ravi', 82), ('Dev', 78)]
classify = lambda n: "even" if n % 2 == 0 else "odd"
print(classify(7), classify.__name__) # odd <lambda>
print((lambda x, y=5: x * y)(4)) # 20
Lambda Functions: Anonymous One-Line Functions in Python Quick Reference & Comparison Table
| Aspect | lambda Function | def Function |
|---|---|---|
| Body restriction | Single expression only (no statements) | Unlimited statements and multi-line blocks |
| Return mechanism | Implicitly returns expression result | Requires explicit return else returns None |
| __name__ attribute | Always '<lambda>' | Takes explicit function identifier name |
| Docstring & annotations | Neither supported inside syntax | Supports __doc__ and __annotations__ |
Lambda Functions: Anonymous One-Line Functions in Python Top 20 Bilingual MCQs with Answers
Q1. What does `print((lambda x, y: x ** y)(2, 3))` output?
(`print((lambda x, y: x ** y)(2, 3))` का आउटपुट क्या होगा?)
(A) SyntaxError
(B) 6
(C) 8
(D) 9
Correct Answer: (C)
[EN] The lambda computes 2 ** 3 = 8 and returns it implicitly upon immediate invocation.
[HI] यह लैम्ब्डा तत्काल कॉल होकर 2 ** 3 = 8 की गणना करता है और स्वतः 8 लौटाता है।
Q2. What happens if you write `f = lambda x: return x + 1` in Python?
(पायथन में `f = lambda x: return x + 1` लिखने पर क्या होगा?)
(A) f(1) returns None
(B) TypeError
(C) SyntaxError because lambda cannot contain a return statement
(D) f(1) returns 2 normally
Correct Answer: (C)
[EN] Lambda bodies accept only a single expression; `return` is a statement and triggers SyntaxError.
[HI] लैम्ब्डा बॉडी में केवल एक एक्सप्रेशन हो सकता है; `return` एक स्टेटमेंट होने के कारण SyntaxError देता है।
Q3. What is the `__name__` attribute of a function created with `fn = lambda a: a * 2`?
(`fn = lambda a: a * 2` से बने फंक्शन का `__name__` एट्रिब्यूट क्या होता है?)
(A) None
(B) 'anonymous'
(C) '<lambda>'
(D) 'fn'
Correct Answer: (C)
[EN] All lambda functions receive the default `__name__` string `'<lambda>'` regardless of variable assignment.
[HI] किसी वेरिएबल को असाइन करने पर भी सभी लैम्ब्डा फंक्शन्स का `__name__` हमेशा `'<lambda>'` होता है।
Q4. Which expression is VALID inside a Python `lambda` body?
(इनमें से कौन-सा विकल्प पायथन के `lambda` बॉडी के भीतर पूरी तरह वैध (VALID) है?)
(A) lambda x: 'pos' if x > 0 else 'non-pos'
(B) lambda x: if x > 0: 'pos'
(C) lambda x: y = x + 1
(D) lambda x: pass
Correct Answer: (A)
[EN] The ternary conditional expression (`a if cond else b`) is an expression, whereas statement `if:`, `pass`, and `=` are statements.
[HI] टर्नरी कंडीशनल (`a if cond else b`) एक एक्सप्रेशन है, जबकि `if:` ब्लॉक, `pass` और `=` स्टेटमेंट्स हैं जो लैम्ब्डा में अवैध हैं।
Q5. What does `funcs = [lambda: i for i in range(3)]; print([f() for f in funcs])` print?
(`funcs = [lambda: i for i in range(3)]; print([f() for f in funcs])` क्या प्रिंट करेगा?)
(A) [2, 2, 2]
(B) NameError
(C) [0, 1, 2]
(D) [0, 0, 0]
Correct Answer: (A)
[EN] Due to late binding in closures, `i` is looked up when each lambda runs after the loop finishes with `i == 2`.
[HI] क्लोज़र की लेट-बाइंडिंग के कारण लूप पूरा होने के बाद कॉल करने पर सभी लैम्ब्डा `i` का अंतिम मान 2 ही पढ़ते हैं।
Q6. How do you fix the loop closure late-binding trap in `[lambda: i for i in range(3)]` so calling them outputs `[0, 1, 2]`?
(`[lambda: i for i in range(3)]` में लेट-बाइंडिंग क्लोज़र ट्रैप को सुधारकर `[0, 1, 2]` पाने का सही तरीका क्या है?)
(A) [lambda: return i for i in range(3)]
(B) [lambda: global i for i in range(3)]
(C) [lambda i=i: i for i in range(3)]
(D) [lambda *i: i for i in range(3)]
Correct Answer: (C)
[EN] Setting `i=i` binds each loop iteration's current value eagerly into that lambda's `__defaults__`.
[HI] `i=i` लिखने से प्रत्येक चक्र का वर्तमान मान डिफ़ॉल्ट आर्गुमेंट के रूप में तुरंत लॉक हो जाता है और `[0, 1, 2]` मिलता है।
Q7. What does `sorted(['banana', 'pie', 'fig', 'apple'], key=lambda w: (len(w), w))` return?
(`sorted(['banana', 'pie', 'fig', 'apple'], key=lambda w: (len(w), w))` क्या लौटाएगा?)
(A) ['banana', 'apple', 'pie', 'fig']
(B) ['apple', 'banana', 'fig', 'pie']
(C) ['pie', 'fig', 'apple', 'banana']
(D) ['fig', 'pie', 'apple', 'banana']
Correct Answer: (D)
[EN] The key tuple sorts primarily by word length (3, 3, 5, 6) and breaks the length-3 tie alphabetically ('fig' before 'pie').
[HI] की-टपल पहले शब्द की लंबाई (3, 3, 5, 6) से और समान लंबाई होने पर वर्णानुक्रम ('fig' पहले 'pie' बाद में) से सॉर्ट करता है।
Q8. What does `type(lambda x: x)` evaluate to in Python?
(पायथन में `type(lambda x: x)` का परिणाम क्या होता है?)
(A) <class 'method'>
(B) <class 'lambda'>
(C) <class 'expression'>
(D) <class 'function'>
Correct Answer: (D)
[EN] A lambda creates the exact same underlying `function` class object as `def`.
[HI] लैम्ब्डा भी `def` की तरह ही `<class 'function'>` प्रकार का सामान्य फंक्शन ऑब्जेक्ट बनाता है।
Q9. Which lambda correctly takes zero arguments and returns True?
(कौन-सा लैम्ब्डा शून्य आर्गुमेंट लेकर True लौटाता है?)
(A) lambda(): True
(B) lambda None: True
(C) lambda: True
(D) lambda void: True
Correct Answer: (C)
[EN] Zero-parameter lambdas place no identifiers between `lambda` and `:`; adding parentheses `lambda():` is a SyntaxError.
[HI] शून्य-पैरामीटर लैम्ब्डा में `lambda` और `:` के बीच कुछ नहीं लिखा जाता (`lambda: True`); कोष्ठक `lambda():` लगाने पर SyntaxError आता है।
Q10. What is the output of `(lambda *args: sum(args))(10, 20, 30)`?
(`(lambda *args: sum(args))(10, 20, 30)` का आउटपुट क्या होगा?)
(A) 60
(B) SyntaxError
(C) TypeError
(D) (10, 20, 30)
Correct Answer: (A)
[EN] Lambda supports `*args` packing just like `def`; `args` receives `(10, 20, 30)` and `sum(args)` returns `60`.
[HI] लैम्ब्डा भी `*args` स्वीकार करता है; `args` को `(10, 20, 30)` मिलता है और `sum(args)` से `60` लौटता है।
Q11. What happens when writing `add = lambda x: int, y: int: x + y`?
(`add = lambda x: int, y: int: x + y` लिखने पर क्या होता है?)
(A) It returns a tuple of ints
(B) TypeError at runtime
(C) SyntaxError because lambda parameters do not support type annotations
(D) It creates a type-checked lambda function
Correct Answer: (C)
[EN] Because `:` delimits the parameter list from the expression body, type hints are disallowed in lambda headers.
[HI] चूँकि `:` पैरामीटर सूची और बॉडी को अलग करता है, इसलिए लैम्ब्डा हेडर में टाइप एनोटेशन लिखने पर SyntaxError आता है।
Q12. Why does PEP 8 (E731) discourage writing `f = lambda x: x + 1`?
(PEP 8 (E731) `f = lambda x: x + 1` लिखने को हतोत्साहित क्यों करता है?)
(A) Using `def f(x): return x + 1` provides a proper function name in tracebacks and supports docstrings
(B) Assigned lambdas cannot accept default parameters
(C) Assigning a lambda to a variable raises DeprecationWarning in Python 3.12
(D) Named lambdas run 10x slower than def functions
Correct Answer: (A)
[EN] A `def` statement binds `__name__` cleanly for debugging/tracebacks, whereas an assigned lambda always shows `<lambda>`.
[HI] `def` से बने फंक्शन एरर ट्रेसबैक में सही नाम दिखाते हैं और डॉकस्ट्रिंग रख सकते हैं, जबकि लैम्ब्डा हमेशा `<lambda>` दिखाता है।
Q13. What does `f = lambda x, y=2: x * y; print(f(5))` output?
(`f = lambda x, y=2: x * y; print(f(5))` का आउटपुट क्या होगा?)
(A) 10
(B) TypeError
(C) 25
(D) 7
Correct Answer: (A)
[EN] Default arguments work identically in lambdas: `x=5` and default `y=2` evaluate to `10`.
[HI] लैम्ब्डा में भी डिफ़ॉल्ट पैरामीटर सामान्य फंक्शन की तरह काम करते हैं: `x=5` और डिफ़ॉल्ट `y=2` से `10` मिलता है।
Q14. Can a lambda function directly accept a multiline docstring inside its body?
(क्या किसी लैम्ब्डा फंक्शन की बॉडी में सीधे डॉकस्ट्रिंग रखी जा सकती है?)
(A) Only in Python 3.11+
(B) Yes, inside parentheses before the colon
(C) No; a lambda body holds only one expression, so no separate docstring statement can precede it
(D) Yes, right after the colon on a new line
Correct Answer: (C)
[EN] Since a lambda allows only a single expression (returned as its result), you cannot place a docstring statement inside it.
[HI] लैम्ब्डा में केवल एक एक्सप्रेशन होता है जो रिटर्न हो जाता है, इसलिए उसमें अलग डॉकस्ट्रिंग स्टेटमेंट नहीं लिखा जा सकता।
Q15. What does `max(['a', 'bbb', 'cc'], key=lambda s: len(s))` return?
(`max(['a', 'bbb', 'cc'], key=lambda s: len(s))` क्या लौटाएगा?)
(A) 'bbb'
(B) 'cc'
(C) ['bbb']
(D) 3
Correct Answer: (A)
[EN] `key` evaluates length for comparison, while `max()` returns the original element `'bbb'` having the maximum key.
[HI] `key` तुलना के लिए लंबाई निकालता है, और `max()` अधिकतम लंबाई वाला मूल तत्व `'bbb'` लौटाता है।
Q16. Which statement about Python `lambda` functions is NOT true?
(पायथन के `lambda` फंक्शन्स के बारे में निम्नलिखित में से कौन-सा कथन असत्य (NOT true) है?)
(A) A lambda implicitly returns the result of its single expression
(B) A lambda creates a regular function object of type `function`
(C) A lambda supports `*args`, `**kwargs`, and default parameter values
(D) A lambda function can contain multiple sequential statements separated by newlines
Correct Answer: (D)
[EN] Lambdas are restricted strictly to a single expression; multi-statement blocks require `def`.
[HI] लैम्ब्डा केवल एक सिंगल एक्सप्रेशन तक सीमित होते हैं; एकाधिक स्टेटमेंट्स के लिए `def` का उपयोग आवश्यक है।
Q17. Within Lambda Functions: Anonymous One-Line Functions in Python, which aspect directly maps to: "Single expression only (no statements)"?
(Lambda Functions: Anonymous One-Line Functions in Python में कौन सा Aspect सीधे "Single expression only (no statements)" से संबंधित है?)
(A) Docstring & annotations
(B) __name__ attribute
(C) Return mechanism
(D) Body restriction
Correct Answer: (D)
[EN] In Lambda Functions: Anonymous One-Line Functions in Python, 'Body restriction' handles 'Single expression only (no statements)' (Unlimited statements and multi-line blocks).
[HI] Lambda Functions: Anonymous One-Line Functions in Python में 'Body restriction' का कार्य/विवरण 'Single expression only (no statements)' (Unlimited statements and multi-line blocks) है।
Q18. Which option accurately describes 'Return mechanism' in Lambda Functions: Anonymous One-Line Functions in Python?
(Lambda Functions: Anonymous One-Line Functions in Python के संदर्भ में 'Return mechanism' की सही विशेषता कौन सी है?)
(A) Implicitly returns expression result
(B) Single expression only (no statements)
(C) Neither supported inside syntax
(D) Always '<lambda>'
Correct Answer: (A)
[EN] 'Return mechanism' provides 'Implicitly returns expression result' — key point: Requires explicit return else returns None.
[HI] 'Return mechanism' का मुख्य विवरण 'Implicitly returns expression result' है (Requires explicit return else returns None)।
Q19. In Lambda Functions: Anonymous One-Line Functions in Python, identify the correct parameter for the specification: "Always '<lambda>'".
(Lambda Functions: Anonymous One-Line Functions in Python में "Always '<lambda>'" विवरण किस विकल्प के लिए सही है?)
(A) __name__ attribute
(B) Return mechanism
(C) Docstring & annotations
(D) Body restriction
Correct Answer: (A)
[EN] '__name__ attribute' corresponds to 'Always '<lambda>'' (Takes explicit function identifier name).
[HI] '__name__ attribute' का संबंध 'Always '<lambda>'' (Takes explicit function identifier name) से है।
Q20. Considering Lambda Functions: Anonymous One-Line Functions in Python, what key behavior defines 'Docstring & annotations'?
(Lambda Functions: Anonymous One-Line Functions in Python में 'Docstring & annotations' की मुख्य भूमिका या मान क्या है?)
(A) Single expression only (no statements)
(B) Neither supported inside syntax
(C) Always '<lambda>'
(D) Implicitly returns expression result
Correct Answer: (B)
[EN] 'Docstring & annotations' represents 'Neither supported inside syntax' (Supports __doc__ and __annotations__).
[HI] 'Docstring & annotations' का अर्थ/मान 'Neither supported inside syntax' है (Supports __doc__ and __annotations__)।
Lambda Functions: Anonymous One-Line Functions in Python — Exam FAQs
Q1: Is a `lambda` faster than an equivalent `def` function in Python?
क्या पायथन में `lambda` उसी कार्य वाले `def` फंक्शन की तुलना में तेज चलता है?
[EN] No. Both compile to the exact same `function` object type and bytecode instructions for evaluating the expression; the choice is purely about conciseness and readability.
[HI] नहीं। दोनों लगभग समान बाइटकोड और एक ही `function` ऑब्जेक्ट बनाते हैं; इनका चुनाव केवल कोड की संक्षिप्तता और पठनीयता पर आधारित होता है।
Q2: How can you do conditional logic inside a `lambda` without `if:` statement blocks?
बिना `if:` स्टेटमेंट ब्लॉक के `lambda` के अंदर कंडीशनल लॉजिक कैसे लिखा जाता है?
[EN] Use Python's inline conditional expression syntax: `lambda x: true_val if condition else false_val`. Nested ternary expressions also work for multi-branch logic, though `def` is cleaner for complex branches.
[HI] पायथन के इनलाइन टर्नरी एक्सप्रेशन `lambda x: true_val if condition else false_val` का उपयोग करें। जटिल शर्तों के लिए `def` अधिक स्पष्ट रहता है।
Q3: Can `lambda` functions be recursive?
क्या `lambda` फंक्शन रिकर्सिव (recursive) हो सकता है?
[EN] Yes, if bound to a name (like `fact = lambda n: 1 if n <= 1 else n * fact(n - 1)`), though PEP 8 strongly recommends using `def` for recursive functions.
[HI] हाँ, यदि उसे किसी नाम से जोड़ा जाए (जैसे `fact = lambda n: 1 if n <= 1 else n * fact(n - 1)`), यद्यपि PEP 8 रिकर्सिव कोड के लिए `def` की सलाह देता है।
Post a Comment
Post a Comment