PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Python List Comprehension: Syntax, Expressions, Conditional Filters (लिस्ट कॉम्प्रिहेंशन: सिंटैक्स [x for x in list if condition]) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: Python list comprehensions provide a concise, expressive syntax [expr for x in iterable if cond] to generate new lists from iterables. Executed via the optimized LIST_APPEND bytecode, they avoid manual loop boilerplate while keeping loop variables scoped locally in Python 3.
अध्याय सार: पायथन लिस्ट कॉम्प्रिहेंशन [expr for x in iterable if cond] सिंटैक्स द्वारा किसी भी इटरेबल से नई लिस्ट बनाने का संक्षिप्त और तेज तरीका प्रदान करता है। यह LIST_APPEND बाइटकोड से चलता है और पायथन 3 में लूप वेरिएबल को लोकल स्कोप में सुरक्षित रखता है।
Python List Comprehension: Syntax, Expressions, Conditional Filters: Detailed Notes & Architecture (लिस्ट कॉम्प्रिहेंशन: सिंटैक्स [x for x in list if condition])
1. Basic Syntax, Scope Isolation, and Performance (मूल सिंटैक्स, स्कोप सुरक्षा और प्रदर्शन)
[EN] A standard list comprehension follows [expression for target in iterable] and produces a fresh list without mutating the source iterable. Internally, CPython compiles it into a dedicated frame using the LIST_APPEND bytecode instruction, bypassing repeated Python-level .append() attribute lookups and running noticeably faster than equivalent for loops. In Python 3, the loop variable target stays strictly isolated inside the comprehension's own scope and never overwrites an identically named variable outside.
[HI] सामान्य लिस्ट कॉम्प्रिहेंशन [expression for target in iterable] रूप में होता है और स्रोत इटरेबल को बदले बिना एक नई लिस्ट बनाता है। CPython इसे LIST_APPEND बाइटकोड निर्देश से चलाता है, जिससे बार-बार .append() खोजने का समय बचता है और यह सामान्य for लूप से तेज चलता है। पायथन 3 में इसका लूप वेरिएबल अपने ही स्कोप तक सीमित रहता है और बाहरी वेरिएबल को प्रभावित नहीं करता।
2. Filtering Elements with Trailing if (अंत में if शर्त द्वारा तत्व छांटना)
[EN] Appending a trailing if clause ([expr for x in iterable if condition]) acts as a filter: Python evaluates condition first for each item, and only executes expr and appends the result when condition is truthy. Multiple consecutive if clauses act as logical AND conditions (e.g., [x for x in nums if x > 0 if x % 2 == 0]). Items failing the condition are completely omitted from the output list.
[HI] अंत में if शर्त जोड़ने ([expr for x in iterable if condition]) से तत्व फ़िल्टर होते हैं: पहले शर्त जांची जाती है, और सत्य होने पर ही expr का परिणाम नई लिस्ट में जुड़ता है। एक से अधिक लगातार if शर्तें लॉजिकल AND की तरह काम करती हैं। असत्य होने वाले तत्व आउटपुट लिस्ट से पूरी तरह बाहर कर दिए जाते हैं।
3. Conditional Expressions (if-else) Placement (कंडीशनल एक्सप्रेशन (if-else) का सही स्थान)
[EN] When you want to transform every element differently based on a condition rather than skipping elements, you must use a ternary conditional expression BEFORE the for keyword: [A if cond else B for x in iterable]. Placing an else clause after the for keyword (such as [x for x in nums if x > 0 else 0]) is invalid grammar and immediately raises a SyntaxError.
[HI] जब किसी शर्त के आधार पर हर तत्व को दो अलग मानों में बदलना हो (किसी को छोड़े बिना), तब टर्नरी एक्सप्रेशन हमेशा for कीवर्ड से पहले लिखा जाता है: [A if cond else B for x in iterable]। यदि आप for के बाद if के साथ else लिखते हैं, तो पायथन तुरंत SyntaxError देता है।
4. Nested Loops and 2D Matrix Flattening (नेस्टेड लूप और 2D मैट्रिक्स को समतल करना)
[EN] A single list comprehension can contain multiple for clauses written in the exact same outer-to-inner order as standard nested for loops. For instance, [val for row in matrix for val in row] flattens a 2D list into a 1D list. Conversely, placing one comprehension inside the expression slot ([[0 for _ in range(3)] for _ in range(2)]) creates distinct independent inner lists, avoiding the shared-reference trap of [[0] * 3] * 2.
[HI] एक कॉम्प्रिहेंशन में एक से अधिक for क्लॉज़ बाहरी-से-आंतरिक क्रम में लिखे जा सकते हैं, जैसे [val for row in matrix for val in row] एक 2D मैट्रिक्स को 1D लिस्ट में समतल (flatten) कर देता है। वहीं, एक्सप्रेशन के भीतर दूसरा कॉम्प्रिहेंशन ([[0 for _ in range(3)] for _ in range(2)]) अलग-अलग स्वतंत्र आंतरिक लिस्ट बनाता है, जिससे [[0] * 3] * 2 वाला साझा रेफरेंस बग नहीं होता।
Syntax, Formula & Technical Example (Python List Comprehension: Syntax, Expressions, Conditional Filters)
nums = [1, 2, 3, 4, 5]
squares = [x * x for x in nums] # [1, 4, 9, 16, 25]
evens = [x for x in nums if x % 2 == 0] # [2, 4]
labels = ['E' if x % 2 == 0 else 'O' for x in nums] # ['O', 'E', 'O', 'E', 'O']
mat = [[1, 2], [3, 4]]
flat = [v for row in mat for v in row] # [1, 2, 3, 4]
print(evens, flat) # [2, 4] [1, 2, 3, 4]
Python List Comprehension: Syntax, Expressions, Conditional Filters Quick Reference & Comparison Table
| Comprehension Pattern | Behavior & Output Example | Key Exam Fact |
|---|---|---|
| [x*2 for x in range(3)] | Transforms every item -> [0, 2, 4] | Compiled with LIST_APPEND; isolates loop var in Py3 |
| [x for x in range(5) if x%2] | Filters odd numbers -> [1, 3] | Trailing if skips falsy items; no else allowed here |
| [x if x>0 else 0 for x in a] | Ternary transform on all items | if-else must precede for; prevents SyntaxError |
| [v for r in m for v in r] | Flattens 2D matrix into 1D list | Outer loop appears first, inner loop appears second |
Python List Comprehension: Syntax, Expressions, Conditional Filters Top 20 Bilingual MCQs with Answers
Q1. What is the output of [x**2 for x in range(4)]?
([x**2 for x in range(4)] का आउटपुट क्या होगा?)
(A) (0, 1, 4, 9)
(B) [0, 1, 4]
(C) [1, 4, 9, 16]
(D) [0, 1, 4, 9]
Correct Answer: (D)
[EN] range(4) yields 0, 1, 2, 3; squaring each produces the list [0, 1, 4, 9].
[HI] range(4) से 0, 1, 2, 3 मिलते हैं, जिनके वर्ग करने पर [0, 1, 4, 9] लिस्ट बनती है।
Q2. Where must an if-else conditional expression be placed inside a list comprehension?
(लिस्ट कॉम्प्रिहेंशन में if-else कंडीशनल एक्सप्रेशन कहाँ लिखा जाना चाहिए?)
(A) Before the for keyword
(B) After the for keyword
(C) At the very end after a colon
(D) Inside the iterable expression only
Correct Answer: (A)
[EN] Value-selecting ternary syntax [A if cond else B for x in seq] goes before 'for'; placing 'else' after 'for' raises SyntaxError.
[HI] मान चुनने वाला टर्नरी सिंटैक्स [A if cond else B for x in seq] हमेशा 'for' से पहले आता है; बाद में else लिखने पर SyntaxError आता है।
Q3. What happens when running [x for x in [1, -2, 3] if x > 0 else 0]?
([x for x in [1, -2, 3] if x > 0 else 0] चलाने पर क्या होगा?)
(A) TypeError
(B) SyntaxError
(C) [1, 3]
(D) [1, 0, 3]
Correct Answer: (B)
[EN] The trailing 'if' clause only supports filtering; adding 'else' after 'for' violates Python syntax rules.
[HI] for के बाद वाला 'if' केवल फ़िल्टर करने के लिए होता है; वहां 'else' जोड़ने पर SyntaxError आता है।
Q4. In Python 3, what does x = 99; a = [x for x in range(3)]; print(x) print?
(पायथन 3 में x = 99; a = [x for x in range(3)]; print(x) क्या प्रिंट करेगा?)
(A) NameError
(B) 2
(C) 99
(D) 3
Correct Answer: (C)
[EN] Python 3 executes list comprehensions in an isolated scope so the loop variable x does not overwrite the outer x = 99.
[HI] पायथन 3 में कॉम्प्रिहेंशन अलग स्कोप में चलता है, इसलिए अंदर का x बाहरी x = 99 को नहीं बदलता।
Q5. What is the output of [x + y for x in [1, 2] for y in [10, 20]]?
([x + y for x in [1, 2] for y in [10, 20]] का आउटपुट क्या होगा?)
(A) [11, 12, 21, 22]
(B) [11, 21, 12, 22]
(C) [[11, 21], [12, 22]]
(D) [11, 22]
Correct Answer: (B)
[EN] The outer loop runs x=1 (y=10, 20 -> 11, 21), then x=2 (y=10, 20 -> 12, 22).
[HI] बाहरी लूप पहले x=1 (y=10, 20 से 11, 21) और फिर x=2 (y=10, 20 से 12, 22) के लिए चलता है।
Q6. Which comprehension correctly flattens m = [[1, 2], [3, 4]] into [1, 2, 3, 4]?
(कौन-सा कॉम्प्रिहेंशन m = [[1, 2], [3, 4]] को [1, 2, 3, 4] में समतल करेगा?)
(A) [[n for n in row] for row in m]
(B) [n for row in m for n in row]
(C) [row for row in m]
(D) [n for n in row for row in m]
Correct Answer: (B)
[EN] Nested for clauses preserve outer-to-inner loop order: outer 'for row in m', then inner 'for n in row'.
[HI] नेस्टेड for क्लॉज़ बाहरी-से-आंतरिक क्रम में लिखे जाते हैं: पहले 'for row in m', फिर 'for n in row'।
Q7. What does [x for x in range(10) if x % 2 == 0 if x % 3 == 0] produce?
([x for x in range(10) if x % 2 == 0 if x % 3 == 0] से क्या परिणाम मिलेगा?)
(A) SyntaxError
(B) [0, 2, 3, 4, 6, 8, 9]
(C) [0, 6]
(D) [6]
Correct Answer: (C)
[EN] Chained trailing 'if' clauses act as logical AND (divisible by both 2 and 3), yielding 0 and 6.
[HI] लगातार जुड़े 'if' क्लॉज़ लॉजिकल AND (2 और 3 दोनों से विभाज्य) की तरह काम करते हैं, जिससे [0, 6] मिलता है।
Q8. What type does (x * 2 for x in range(4)) return when enclosed in parentheses instead of brackets?
(कोष्ठक [] के बजाय गोल कोष्ठक () में (x * 2 for x in range(4)) लिखने पर क्या बनता है?)
(A) A list
(B) A generator object
(C) A set
(D) A tuple
Correct Answer: (B)
[EN] Python has no tuple comprehension; parentheses around a comprehension produce a lazy generator object.
[HI] पायथन में टपल कॉम्प्रिहेंशन नहीं होता; () में लिखने पर यह एक लेज़ी जनरेटर ऑब्जेक्ट बनाता है।
Q9. What is the output of [c.upper() for c in 'hi!']?
([c.upper() for c in 'hi!'] का आउटपुट क्या होगा?)
(A) ['H', 'I', '!']
(B) 'HI!'
(C) ['HI!']
(D) TypeError
Correct Answer: (A)
[EN] Iterating over the string yields 'h', 'i', '!', and calling .upper() on each builds ['H', 'I', '!'].
[HI] स्ट्रिंग पर लूप चलने से 'h', 'i', '!' मिलते हैं और .upper() लगने से ['H', 'I', '!'] लिस्ट बनती है।
Q10. What is printed by g = [[0]*2 for _ in range(2)]; g[0][0] = 5; print(g)?
(g = [[0]*2 for _ in range(2)]; g[0][0] = 5; print(g) का आउटपुट क्या होगा?)
(A) [[5, 0], [5, 0]]
(B) [[5, 5], [0, 0]]
(C) [[5, 0], [0, 0]]
(D) TypeError
Correct Answer: (C)
[EN] Because the comprehension evaluates [0]*2 freshly for each row, the two rows are distinct inner lists.
[HI] कॉम्प्रिहेंशन हर पुनरावृत्ति में [0]*2 को अलग से बनाता है, इसलिए दोनों पंक्तियाँ स्वतंत्र रहती हैं।
Q11. What is the output of [x if x > 2 else -1 for x in [1, 3, 2, 4]]?
([x if x > 2 else -1 for x in [1, 3, 2, 4]] का आउटपुट क्या होगा?)
(A) SyntaxError
(B) [-1, 3, -1, 4]
(C) [-1, 1, 3, -1, 2, 4]
(D) [3, 4]
Correct Answer: (B)
[EN] Elements > 2 stay unchanged while others become -1, maintaining the original length of 4.
[HI] 2 से बड़े तत्व वैसे ही रहते हैं और बाकी -1 में बदल जाते हैं, जिससे [-1, 3, -1, 4] मिलता है।
Q12. Which CPython bytecode instruction optimizes list comprehensions over manual .append() loops?
(कौन-सा CPython बाइटकोड निर्देश लिस्ट कॉम्प्रिहेंशन को सामान्य .append() लूप से तेज बनाता है?)
(A) LIST_APPEND
(B) LOAD_METHOD
(C) BUILD_TUPLE
(D) SET_ADD
Correct Answer: (A)
[EN] List comprehensions emit LIST_APPEND, avoiding repeated attribute resolution and function call overhead for .append().
[HI] लिस्ट कॉम्प्रिहेंशन में LIST_APPEND बाइटकोड उपयोग होता है, जिससे बार-बार .append() खोजने का समय बचता है।
Q13. What does [(x, x+1) for x in range(2)] evaluate to?
([(x, x+1) for x in range(2)] का मान क्या होगा?)
(A) [0, 1, 1, 2]
(B) SyntaxError
(C) ((0, 1), (1, 2))
(D) [(0, 1), (1, 2)]
Correct Answer: (D)
[EN] The expression (x, x+1) constructs a 2-tuple for each value of x (0 and 1), yielding [(0, 1), (1, 2)].
[HI] (x, x+1) प्रत्येक x (0 और 1) के लिए टपल बनाता है, जिससे [(0, 1), (1, 2)] प्राप्त होता है।
Q14. Which built-in functional pair does [f(x) for x in seq if p(x)] replace concisely?
([f(x) for x in seq if p(x)] किन दो बिल्ट-इन फंक्शंस के संयोजन का संक्षिप्त विकल्प है?)
(A) any() and all()
(B) zip() and enumerate()
(C) sorted() and reversed()
(D) map() and filter()
Correct Answer: (D)
[EN] The expression f(x) acts like map(f, ...), while the trailing 'if p(x)' acts like filter(p, seq).
[HI] अग्रभाग f(x) map() जैसा काम करता है और अंत में 'if p(x)' filter() जैसा कार्य करता है।
Q15. What happens if the input iterable in a list comprehension is empty, e.g., [x*2 for x in []]?
(यदि इनपुट इटरेबल खाली हो, जैसे [x*2 for x in []], तो क्या परिणाम होगा?)
(A) StopIteration
(B) [None]
(C) ValueError
(D) []
Correct Answer: (D)
[EN] Iterating over an empty sequence executes zero iterations and cleanly evaluates to an empty list [].
[HI] खाली इटरेबल पर लूप शून्य बार चलता है और बिना किसी त्रुटि के खाली लिस्ट [] बनती है।
Q16. Which statement is NOT true about Python list comprehensions?
(पायथन लिस्ट कॉम्प्रिहेंशन के बारे में कौन-सा कथन सत्य नहीं है?)
(A) They modify the original source list in place
(B) Their loop variable does not leak to the outer scope in Python 3
(C) They can contain nested for loops
(D) They always return a new list object
Correct Answer: (A)
[EN] A list comprehension always creates and returns a brand-new list; it never mutates the input iterable in place.
[HI] लिस्ट कॉम्प्रिहेंशन कभी भी मूल स्रोत लिस्ट को इन-प्लेस नहीं बदलता; यह हमेशा एक नई लिस्ट लौटाता है।
Q17. Within Python List Comprehension: Syntax, Expressions, Conditional Filters, which comprehension pattern directly maps to: "Transforms every item -> [0, 2, 4]"?
(Python List Comprehension: Syntax, Expressions, Conditional Filters में कौन सा Comprehension Pattern सीधे "Transforms every item -> [0, 2, 4]" से संबंधित है?)
(A) [x if x>0 else 0 for x in a]
(B) [x for x in range(5) if x%2]
(C) [x*2 for x in range(3)]
(D) [v for r in m for v in r]
Correct Answer: (C)
[EN] In Python List Comprehension: Syntax, Expressions, Conditional Filters, '[x*2 for x in range(3)]' handles 'Transforms every item -> [0, 2, 4]' (Compiled with LIST_APPEND; isolates loop var in Py3).
[HI] Python List Comprehension: Syntax, Expressions, Conditional Filters में '[x*2 for x in range(3)]' का कार्य/विवरण 'Transforms every item -> [0, 2, 4]' (Compiled with LIST_APPEND; isolates loop var in Py3) है।
Q18. Which option accurately describes '[x for x in range(5) if x%2]' in Python List Comprehension: Syntax, Expressions, Conditional Filters?
(Python List Comprehension: Syntax, Expressions, Conditional Filters के संदर्भ में '[x for x in range(5) if x%2]' की सही विशेषता कौन सी है?)
(A) Ternary transform on all items
(B) Transforms every item -> [0, 2, 4]
(C) Flattens 2D matrix into 1D list
(D) Filters odd numbers -> [1, 3]
Correct Answer: (D)
[EN] '[x for x in range(5) if x%2]' provides 'Filters odd numbers -> [1, 3]' — key point: Trailing if skips falsy items; no else allowed here.
[HI] '[x for x in range(5) if x%2]' का मुख्य विवरण 'Filters odd numbers -> [1, 3]' है (Trailing if skips falsy items; no else allowed here)।
Q19. In Python List Comprehension: Syntax, Expressions, Conditional Filters, identify the correct parameter for the specification: "Ternary transform on all items".
(Python List Comprehension: Syntax, Expressions, Conditional Filters में "Ternary transform on all items" विवरण किस विकल्प के लिए सही है?)
(A) [x if x>0 else 0 for x in a]
(B) [x for x in range(5) if x%2]
(C) [v for r in m for v in r]
(D) [x*2 for x in range(3)]
Correct Answer: (A)
[EN] '[x if x>0 else 0 for x in a]' corresponds to 'Ternary transform on all items' (if-else must precede for; prevents SyntaxError).
[HI] '[x if x>0 else 0 for x in a]' का संबंध 'Ternary transform on all items' (if-else must precede for; prevents SyntaxError) से है।
Q20. Considering Python List Comprehension: Syntax, Expressions, Conditional Filters, what key behavior defines '[v for r in m for v in r]'?
(Python List Comprehension: Syntax, Expressions, Conditional Filters में '[v for r in m for v in r]' की मुख्य भूमिका या मान क्या है?)
(A) Filters odd numbers -> [1, 3]
(B) Flattens 2D matrix into 1D list
(C) Transforms every item -> [0, 2, 4]
(D) Ternary transform on all items
Correct Answer: (B)
[EN] '[v for r in m for v in r]' represents 'Flattens 2D matrix into 1D list' (Outer loop appears first, inner loop appears second).
[HI] '[v for r in m for v in r]' का अर्थ/मान 'Flattens 2D matrix into 1D list' है (Outer loop appears first, inner loop appears second)।
Python List Comprehension: Syntax, Expressions, Conditional Filters — Exam FAQs
Q1: When is a regular for loop better than a list comprehension?
लिस्ट कॉम्प्रिहेंशन के बजाय सामान्य for लूप का उपयोग कब बेहतर होता है?
[EN] Use a normal for loop when you need side effects (like printing or writing files) without building a list, when complex try/except error handling is needed per item, or when chaining more than two nested loops hurts readability.
[HI] जब आपको लिस्ट बनाए बिना केवल कोई कार्य (जैसे प्रिंट या फाइल लेखन) करना हो, try/except संभालना हो, या बहुत जटिल नेस्टिंग से कोड अस्पष्ट हो रहा हो तब सामान्य for लूप बेहतर है।
Q2: Why shouldn't I write [print(x) for x in items]?
मुझे [print(x) for x in items] क्यों नहीं लिखना चाहिए?
[EN] print() returns None, so [print(x) for x in items] wastes memory allocating a list full of [None, None, ...] that gets discarded immediately. A standard for loop avoids that unnecessary allocation.
[HI] print() हमेशा None लौटाता है, इसलिए ऐसा करने से अनावश्यक रूप से [None, None, ...] वाली एक बेकार लिस्ट मेमोरी में बन जाती है। इसके लिए सामान्य for लूप सही है।
Q3: Can I use break or continue inside a list comprehension?
क्या हम लिस्ट कॉम्प्रिहेंशन के अंदर break या continue का उपयोग कर सकते हैं?
[EN] No. break and continue are statements restricted to standard for and while loops; putting them inside a list comprehension causes a SyntaxError. Use filtering conditions or itertools.takewhile() instead.
[HI] नहीं। break और continue केवल सामान्य for/while लूप में चलते हैं; कॉम्प्रिहेंशन के अंदर इनका उपयोग SyntaxError देता है।
Post a Comment
Post a Comment