Consider the following Assertion and Reason regarding Python Generators:
Assertion (A): Generators in Python return an iterator object with a sequence of values instead of a single value.
Reason (R): In a generator function, the yield statement is used instead of the return statement to produce values.
Which of the following is correct?
🌟 Quick Verification
- Direct Answer: Both A and R are true, and R is the correct explanation of A.
- Core Concept: The mechanism of Generators and the yield keyword.
🧠 Concept Blueprint
- The Core Entity: Generators:
- Generators are a memory-efficient way to create iterators.
- Instead of computing all values at once and storing them in memory, they generate values on-the-fly.
- Why It is Correct:
- The Assertion is correct because generators are specifically designed to return an iterator object that yields a sequence.
- The Reason is correct because the yield statement is the mechanism that pauses the function, saves its state, and produces a value, which is exactly how generators achieve the behavior described in the assertion.
📊 Fact Spotlight
| Feature | Function | Generator |
|---|---|---|
| Return Type | Single value | Iterator object |
| Keyword | return | yield |
| Memory Usage | High (stores all results) | Low (lazy evaluation) |
💡 Exam Strategy & Trivia
Common Pitfall: A common mistake is thinking yield terminates the function like return. It does not; it pauses execution, allowing the function to resume from where it left off.
Memorable Trivia: Generators are often used for processing large datasets where loading everything into memory at once would cause a crash.