Python Generators (yield Statement) and Generator Expressions Notes in Hindi & English : जनरेटर (Generators): yield स्टेटमेंट, मेमोरी बचत और इटरेटर्स और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Python Generators (yield Statement) and Generator Expressions (जनरेटर (Generators): yield स्टेटमेंट, मेमोरी बचत और इटरेटर्स) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: Generators are Python functions or expressions that emit items lazily one at a time via the yield statement rather than computing and storing an entire sequence in RAM. Every generator implements the iterator protocol (__iter__ and __next__) automatically and suspends its execution state across calls.

अध्याय सार: जनरेटर विशेष पायथन फंक्शन या एक्सप्रेशन होते हैं जो पूरी श्रृंखला को एक साथ मेमोरी में स्टोर करने के बजाय yield स्टेटमेंट से एक-एक करके मान (lazy evaluation) उत्पन्न करते हैं। प्रत्येक जनरेटर स्वतः इटेरेटर प्रोटोकॉल (__iter__ और __next__) लागू करता है और दो कॉल्स के बीच अपनी निष्पादन स्थिति को सुरक्षित रखता है।

Python Generators (yield Statement) and Generator Expressions: Detailed Notes & Architecture (जनरेटर (Generators): yield स्टेटमेंट, मेमोरी बचत और इटरेटर्स)

1. How yield Differs from return in Execution Flow (निष्पादन प्रवाह में yield और return का अंतर)

[EN] When Python encounters a yield keyword inside a def block, calling that function does not run its body immediately—it returns a generator iterator object instead. Unlike return, which exits the function and destroys its local stack frame, yield pauses execution, preserves all local variable bindings and the instruction pointer, and emits one value to next(). Resuming continues immediately after yield until completion raises StopIteration.

[HI] जिस फंक्शन में yield कीवर्ड होता है, उसे कॉल करने पर उसकी बॉडी तुरंत नहीं चलती बल्कि वह एक जनरेटर ऑब्जेक्ट लौटाता है। return फंक्शन को समाप्त करके लोकल स्टैक फ्रेम नष्ट कर देता है, जबकि yield निष्पादन को विराम (pause) देकर सभी लोकल वेरिएबल्स को सुरक्षित रखता है और एक मान लौटाता है। अगली बार next() कॉल करने पर कोड वहीं से आगे चलता है और अंत में StopIteration उठता है।

2. Generator Expressions vs List Comprehensions (जनरेटर एक्सप्रेशन बनाम लिस्ट कॉम्प्रिहेंशन)

[EN] Generator expressions use round parentheses (x * x for x in range(10**6)) instead of the square brackets used by list comprehensions. While a list comprehension allocates all one million integers eagerly in memory (O(n) space), a generator expression occupies constant O(1) auxiliary memory (~104-200 bytes) and can even model infinite streams. Note that generators are single-pass: once exhausted, iterating again yields zero elements.

[HI] जनरेटर एक्सप्रेशन में लिस्ट कॉम्प्रिहेंशन के बड़े कोष्ठक [] के बजाय छोटे कोष्ठक () का उपयोग होता है, जैसे (x * x for x in range(10**6))। लिस्ट कॉम्प्रिहेंशन पूरी सूची तुरंत मेमोरी में बनाता है (O(n) स्पेस), जबकि जनरेटर एक्सप्रेशन आवश्यकता पड़ने पर ही मान गिनता है (O(1) स्थिर मेमोरी) और अनंत श्रृंखला भी दर्शा सकता है। ध्यान रहे जनरेटर केवल एक बार (single-pass) चलने के बाद समाप्त (exhaust) हो जाते हैं।

3. Sub-generators with yield from and Generator Methods (yield from और जनरेटर के उन्नत मेथड्स (send, close))

[EN] Introduced in Python 3.3 (PEP 380), yield from iterable delegates iteration directly to another generator or iterable without writing an explicit inner for loop. Generators also expose coroutine-like control methods: gen.send(val) injects a value into the suspended yield expression (after priming with next(gen) or gen.send(None)), gen.throw(exc) injects an exception, and gen.close() triggers GeneratorExit for cleanup.

[HI] पायथन 3.3 (PEP 380) में जोड़ा गया yield from सीधे किसी अन्य जनरेटर या इटेरेबल को बिना अलग लूप लिखे आगे मान उत्पन्न करने की जिम्मेदारी सौंप देता है। इसके अलावा जनरेटर में तीन विशेष मेथड होते हैं: gen.send(val) रुके हुए yield में बाहर से मान भेजता है (पहले next() या send(None) से प्राइम करना जरूरी है), gen.throw() एक्सेप्शन भेजता है और gen.close() GeneratorExit उठाकर सफाई करता है।

4. Streaming Data Pipelines and itertools Integration (डेटा पाइपलाइन और itertools के साथ उपयोग)

[EN] Generators shine when processing multi-gigabyte log files, CSV feeds, or database cursors line by line without loading the entire dataset into RAM. Chaining multiple generator expressions with built-ins like sum(), any(), all(), or itertools.islice() builds memory-flat pipelines where each item flows stage by stage. If a generator executes return value, Python attaches value to StopIteration.value.

[HI] कई गीगाबाइट की लॉग फाइलों या डेटाबेस स्ट्रीम को एक बार में RAM में लोड किए बिना लाइन-दर-लाइन प्रोसेस करने में जनरेटर अत्यंत उपयोगी होते हैं। कई जनरेटर एक्सप्रेशन को sum(), any() या itertools.islice() से जोड़कर कम मेमोरी में तेज डेटा पाइपलाइन बनाई जा सकती है। यदि जनरेटर के अंदर return value लिखा जाए, तो वह मान अंतिम StopIteration.value में उपलब्ध होता है।

Syntax, Formula & Technical Example (Python Generators (yield Statement) and Generator Expressions)

def fibonacci(limit):
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b

gen = fibonacci(10)
print(list(gen))
print(list(gen))

Python Generators (yield Statement) and Generator Expressions Quick Reference & Comparison Table

Comparison AspectPython GeneratorList / Regular Function
Evaluation TimingLazy; computes next value on demandEager; computes entire result upfront
Memory ComplexityO(1) constant stack frame storageO(n) proportional to collection size
Iteration PassSingle-pass; exhausted after completionReusable across unlimited for-loops
Keyword & Frameyield suspends and preserves local statereturn terminates and discards frame

Python Generators (yield Statement) and Generator Expressions Top 20 Bilingual MCQs with Answers

Q1. What does calling a generator function (containing yield) immediately return?

(जिस फंक्शन में yield हो, उसे पहली बार कॉल करने पर वह तुरंत क्या लौटाता है?)

(A) A list containing all generated items

(B) A generator iterator object without executing the body yet

(C) None until a return statement is reached

(D) The first yielded value immediately

Correct Answer: (B)

[EN] Calling a generator function creates and returns a generator object; code inside begins executing only on the first next().

[HI] जनरेटर फंक्शन को कॉल करने पर उसका कोड तुरंत नहीं चलता, बल्कि एक जनरेटर ऑब्जेक्ट मिलता है जो पहले next() पर चलना शुरू होता है।

Q2. What output does the fibonacci snippet above print on its two print statements?

(ऊपर दिए गए fibonacci कोड के दोनों print स्टेटमेंट क्या आउटपुट देंगे?)

(A) [0, 1, 1, 2, 3, 5, 8] twice

(B) [0] then [1]

(C) [0, 1, 1, 2, 3, 5, 8] then []

(D) [0, 1, 1, 2, 3, 5, 8, 13] then []

Correct Answer: (C)

[EN] The first list(gen) consumes all yielded Fibonacci numbers <= 10; the second list(gen) sees an exhausted generator and returns [].

[HI] पहला list(gen) 10 तक की सभी संख्याएं [0, 1, 1, 2, 3, 5, 8] निकाल लेता है; जनरेटर समाप्त होने के कारण दूसरा list(gen) खाली [] देता है।

Q3. Which exception is raised automatically when a generator finishes and next() is called again?

(जनरेटर के सभी मान समाप्त होने के बाद पुनः next() कॉल करने पर कौन-सा एक्सेप्शन स्वतः उत्पन्न होता है?)

(A) EOFError

(B) IndexError

(C) GeneratorExit

(D) StopIteration

Correct Answer: (D)

[EN] All Python iterators, including generators, signal exhaustion by raising StopIteration.

[HI] सभी इटेरेटर्स की तरह जनरेटर भी समाप्त होने की सूचना StopIteration एक्सेप्शन उठाकर देते हैं।

Q4. Which syntax creates a generator expression in Python?

(पायथन में जनरेटर एक्सप्रेशन बनाने का सही सिंटैक्स कौन-सा है?)

(A) {x * 2 for x in range(5)}

(B) <x * 2 for x in range(5)>

(C) (x * 2 for x in range(5))

(D) [x * 2 for x in range(5)]

Correct Answer: (C)

[EN] Parentheses create a generator expression, whereas [] creates a list comprehension and {} creates a set comprehension.

[HI] छोटे कोष्ठक () जनरेटर एक्सप्रेशन बनाते हैं, जबकि [] लिस्ट और {} सेट कॉम्प्रिहेंशन बनाते हैं।

Q5. Which two dunder methods does every Python generator object implement automatically?

(पायथन में प्रत्येक जनरेटर ऑब्जेक्ट स्वतः कौन-से दो डंडर मेथड्स लागू करता है?)

(A) __getitem__ and __len__

(B) __yield__ and __stop__

(C) __enter__ and __exit__

(D) __iter__ and __next__

Correct Answer: (D)

[EN] Every generator is an iterator, implementing both __iter__() (returning self) and __next__().

[HI] प्रत्येक जनरेटर स्वयं एक इटेरेटर होता है, इसलिए उसमें __iter__() और __next__() दोनों मेथड्स होते हैं।

Q6. What happens if you call gen.send(42) on a newly created generator before priming it with next(gen) or send(None)?

(किसी नए बने जनरेटर को next(gen) या send(None) से प्राइम किए बिना सीधे gen.send(42) कॉल करने पर क्या होता है?)

(A) TypeError: can't send non-None value to a just-started generator

(B) StopIteration(42) is raised

(C) 42 is silently stored as the first local variable

(D) The generator skips the first yield and returns 42

Correct Answer: (A)

[EN] A fresh generator sits at the top of its body before reaching the first yield, so only None can be sent initially.

[HI] नया जनरेटर पहले yield तक पहुँचा ही नहीं होता, अतः पहले next() या send(None) चलाए बिना गैर-None मान भेजने पर TypeError आता है।

Q7. In which Python version was the yield from syntax introduced via PEP 380?

(PEP 380 के तहत yield from सिंटैक्स को पायथन के किस संस्करण में जोड़ा गया था?)

(A) Python 3.0

(B) Python 2.7

(C) Python 3.3

(D) Python 3.8

Correct Answer: (C)

[EN] Python 3.3 introduced yield from to delegate transparently to sub-generators.

[HI] पायथन 3.3 में सब-जनरेटर्स को आसानी से डेलिगेट करने हेतु yield from जोड़ा गया।

Q8. What exception is injected inside a paused generator when gen.close() is invoked?

(जब किसी रुके हुए जनरेटर पर gen.close() कॉल किया जाता है, तो उसके भीतर कौन-सा एक्सेप्शन भेजा जाता है?)

(A) StopIteration

(B) KeyboardInterrupt

(C) RuntimeError

(D) GeneratorExit

Correct Answer: (D)

[EN] Calling gen.close() raises GeneratorExit at the paused yield point so try/finally cleanup blocks execute.

[HI] gen.close() कॉल करने पर yield बिंदु पर GeneratorExit उठता है ताकि जनरेटर सफाई करके बंद हो सके।

Q9. What is the auxiliary space complexity of iterating (x for x in range(10_000_000)) compared to [x for x in range(10_000_000)]?

([x for x in range(10_000_000)] की तुलना में (x for x in range(10_000_000)) को इटरेट करने की मेमोरी जटिलता क्या है?)

(A) O(log n) for the generator vs O(n^2) for the list

(B) O(1) for the generator expression vs O(n) for the list comprehension

(C) O(n) for generator vs O(1) for list

(D) O(n) for both

Correct Answer: (B)

[EN] Generator expressions yield one item at a time in constant O(1) memory, whereas lists materialize all n references.

[HI] जनरेटर एक्सप्रेशन एक समय में एक ही मान रखता है (O(1) स्पेस), जबकि लिस्ट सभी 1 करोड़ मान RAM में भरती है (O(n) स्पेस)।

Q10. If a generator executes return 'done', where can the caller inspect 'done'?

(यदि कोई जनरेटर फंक्शन return 'done' निष्पादित करता है, तो कॉलर को 'done' मान कहाँ प्राप्त होता है?)

(A) Python forbids return statements inside generators with SyntaxError

(B) It overwrites the generator variable itself

(C) It is yielded as the final element inside a for-loop

(D) In the .value attribute of the raised StopIteration exception

Correct Answer: (D)

[EN] In Python 3, return value inside a generator raises StopIteration(value), storing the return object on exc.value.

[HI] पायथन 3 में जनरेटर के अंदर return value करने पर StopIteration(value) उठता है जिसके .value एट्रिब्यूट में वह मान मिलता है।

Q11. Can a Python generator represent an infinite sequence (such as all natural numbers) without crashing RAM?

(क्या पायथन जनरेटर बिना RAM क्रैश किए एक अनंत श्रृंखला (जैसे सभी प्राकृतिक संख्याएं) का प्रतिनिधित्व कर सकता है?)

(A) Only if sys.setrecursionlimit is increased

(B) Only with list comprehensions

(C) No, Python raises MemoryError before creating an infinite generator

(D) Yes, using an infinite while True: loop with yield

Correct Answer: (D)

[EN] Because values are computed lazily on each next() call, while True: yield n uses constant memory indefinitely.

[HI] चूंकि मान केवल next() मांगने पर ही बनते हैं, इसलिए while True: yield n से बिना मेमोरी भरे अनंत स्ट्रीम बनाई जा सकती है।

Q12. What happens if you pass a generator expression as the sole argument to a function like sum(x*x for x in nums)?

(जब sum(x*x for x in nums) जैसे फंक्शन में जनरेटर एक्सप्रेशन एकमात्र आर्ग्यूमेंट हो, तो सिंटैक्स नियम क्या कहता है?)

(A) Extra inner parentheses may be omitted cleanly

(B) Double parentheses sum((...)) are strictly mandatory or SyntaxError occurs

(C) It returns a generator instead of an integer

(D) sum() converts it to a list automatically before iterating

Correct Answer: (A)

[EN] Python grammar allows omitting redundant generator parentheses when it is the single argument to a function call.

[HI] यदि फंक्शन कॉल में जनरेटर एक्सप्रेशन अकेला आर्ग्यूमेंट हो, तो दोहरे कोष्ठक लगाना अनिवार्य नहीं होता।

Q13. Which standard library module provides generator-based combinators like islice, chain, and count?

(पायथन की किस स्टैंडर्ड लाइब्रेरी में islice, chain और count जैसे जनरेटर-आधारित फंक्शन उपलब्ध हैं?)

(A) collections

(B) functools

(C) generators

(D) itertools

Correct Answer: (D)

[EN] The itertools module implements fast C-level lazy iterators compatible with generator pipelines.

[HI] itertools मॉड्यूल जनरेटर पाइपलाइन के लिए तेज और मेमोरी-कुशल लेज़ी इटेरेटर टूल्स प्रदान करता है।

Q14. Why can you NOT index a generator object directly with gen[0] or compute len(gen)?

(किसी जनरेटर ऑब्जेक्ट पर सीधे gen[0] इंडेक्सिंग या len(gen) क्यों नहीं चल पाता?)

(A) Generators produce items lazily on the fly and do not store a sequence or known length in memory

(B) Because generators are encrypted objects

(C) Because generators always have infinite length

(D) Because len() only works on integers and strings

Correct Answer: (A)

[EN] A generator implements iterator __next__, not sequence __getitem__ or __len__.

[HI] जनरेटर पूरे डेटा को मेमोरी में नहीं रखता और न ही पहले से उसकी लंबाई जानता है, इसलिए इंडेक्सिंग या len() समर्थित नहीं है।

Q15. Which statement about Python generators is NOT true?

(पायथन जनरेटर्स के बारे में निम्नलिखित में से कौन-सा कथन असत्य है?)

(A) A function containing yield always returns a generator object

(B) Generator expressions use parentheses instead of square brackets

(C) Generators preserve local variable states across successive next() calls

(D) A generator object can be looped over multiple times to re-read the same values automatically

Correct Answer: (D)

[EN] Generators are single-use iterators; once exhausted, a fresh generator instance must be created to iterate again.

[HI] जनरेटर को केवल एक ही बार लूप किया जा सकता है; समाप्त होने के बाद पुनः पढ़ने के लिए नया जनरेटर बनाना पड़ता है।

Q16. What does iter(gen) is gen evaluate to for any Python generator object gen?

(किसी भी पायथन जनरेटर ऑब्जेक्ट gen के लिए iter(gen) is gen का मान क्या होता है?)

(A) TypeError

(B) None

(C) True

(D) False

Correct Answer: (C)

[EN] Like all proper Python iterators, a generator's __iter__() method returns self.

[HI] सभी मानक इटेरेटर्स की तरह जनरेटर का __iter__() मेथड स्वयं उसी ऑब्जेक्ट (self) को लौटाता है।

Q17. Within Python Generators (yield Statement) and Generator Expressions, which comparison aspect directly maps to: "Lazy; computes next value on demand"?

(Python Generators (yield Statement) and Generator Expressions में कौन सा Comparison Aspect सीधे "Lazy; computes next value on demand" से संबंधित है?)

(A) Iteration Pass

(B) Keyword & Frame

(C) Evaluation Timing

(D) Memory Complexity

Correct Answer: (C)

[EN] In Python Generators (yield Statement) and Generator Expressions, 'Evaluation Timing' handles 'Lazy; computes next value on demand' (Eager; computes entire result upfront).

[HI] Python Generators (yield Statement) and Generator Expressions में 'Evaluation Timing' का कार्य/विवरण 'Lazy; computes next value on demand' (Eager; computes entire result upfront) है।

Q18. Which option accurately describes 'Memory Complexity' in Python Generators (yield Statement) and Generator Expressions?

(Python Generators (yield Statement) and Generator Expressions के संदर्भ में 'Memory Complexity' की सही विशेषता कौन सी है?)

(A) yield suspends and preserves local state

(B) Lazy; computes next value on demand

(C) Single-pass; exhausted after completion

(D) O(1) constant stack frame storage

Correct Answer: (D)

[EN] 'Memory Complexity' provides 'O(1) constant stack frame storage' — key point: O(n) proportional to collection size.

[HI] 'Memory Complexity' का मुख्य विवरण 'O(1) constant stack frame storage' है (O(n) proportional to collection size)।

Q19. In Python Generators (yield Statement) and Generator Expressions, identify the correct parameter for the specification: "Single-pass; exhausted after completion".

(Python Generators (yield Statement) and Generator Expressions में "Single-pass; exhausted after completion" विवरण किस विकल्प के लिए सही है?)

(A) Keyword & Frame

(B) Evaluation Timing

(C) Iteration Pass

(D) Memory Complexity

Correct Answer: (C)

[EN] 'Iteration Pass' corresponds to 'Single-pass; exhausted after completion' (Reusable across unlimited for-loops).

[HI] 'Iteration Pass' का संबंध 'Single-pass; exhausted after completion' (Reusable across unlimited for-loops) से है।

Q20. Considering Python Generators (yield Statement) and Generator Expressions, what key behavior defines 'Keyword & Frame'?

(Python Generators (yield Statement) and Generator Expressions में 'Keyword & Frame' की मुख्य भूमिका या मान क्या है?)

(A) yield suspends and preserves local state

(B) O(1) constant stack frame storage

(C) Single-pass; exhausted after completion

(D) Lazy; computes next value on demand

Correct Answer: (A)

[EN] 'Keyword & Frame' represents 'yield suspends and preserves local state' (return terminates and discards frame).

[HI] 'Keyword & Frame' का अर्थ/मान 'yield suspends and preserves local state' है (return terminates and discards frame)।

Python Generators (yield Statement) and Generator Expressions — Exam FAQs

Q1: How do generators save memory compared to functions returning lists?

लिस्ट लौटाने वाले फंक्शन की तुलना में जनरेटर मेमोरी कैसे बचाते हैं?

[EN] A list-returning function builds and stores every single element in RAM simultaneously before returning, whereas a generator computes and yields just one element per next() call while keeping only its current stack frame in memory.

[HI] लिस्ट वाला फंक्शन एक साथ सभी तत्व मेमोरी में तैयार कर लेता है, जबकि जनरेटर एक समय में केवल एक ही मान बनाकर लौटाता है और केवल अपनी वर्तमान स्थिति को ही मेमोरी में रखता है।

Q2: Can a generator function contain both yield and return statements?

क्या एक ही जनरेटर फंक्शन के अंदर yield और return दोनों स्टेटमेंट हो सकते हैं?

[EN] Yes. In Python 3, executing return value inside a generator terminates iteration early and passes value inside the StopIteration(value) exception.

[HI] हाँ। पायथन 3 में जनरेटर के भीतर return लिखने से जनरेटर रुक जाता है और लौटाया गया मान StopIteration एक्सेप्शन के .value एट्रिब्यूट में मिल जाता है।

Q3: When should I use a list comprehension instead of a generator expression?

जनरेटर एक्सप्रेशन के बजाय लिस्ट कॉम्प्रिहेंशन का उपयोग कब करना चाहिए?

[EN] Choose a list comprehension when you need random indexing (items[i]), length via len(items), sorting, or multiple passes over a moderately sized dataset.

[HI] जब आपको इंडेक्स से तत्व उठाना हो (items[i]), len() निकालना हो, सॉर्टिंग करनी हो या डेटा पर कई बार लूप चलाना हो, तब लिस्ट कॉम्प्रिहेंशन बेहतर रहता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)