Generators Questions and Answers
Practice ModeShowing 10 of 25 questions
Q11
What is the difference between return and yield?
Answer: Option A
Explanation: return terminates the function completely, while yield pauses the function and remembers its state for next call.
Q12
Can generators be used with infinite sequences?
Answer: Option A
Explanation: Generators are ideal for infinite sequences as they generate values on demand without storing them all in memory.
Q13
How do you create a generator that yields numbers from 0 to n?
Answer: Option A
Explanation: Generator functions use yield to produce values one at a time within a loop.
Q14
What is generator comprehension?
Answer: Option A
Explanation: Generator comprehension uses parentheses and creates generator objects similar to list comprehensions but lazily.
Q15
Can you send values back into a generator?
Answer: Option A
Explanation: Generators can receive values using the send() method, allowing two-way communication between caller and generator.
Q16
What does the close() method do on a generator?
Answer: Option A
Explanation: The close() method raises GeneratorExit exception at the point where the generator was paused, terminating it.
Q17
What is the purpose of yield from in Python?
Answer: Option A
Explanation: yield from is used to delegate to another generator, simplifying code when working with nested generators.
Q18
Can generators be pickled in Python?
Answer: Option A
Explanation: Generators cannot be pickled because they contain execution state that cannot be serialized.
Q19
What is the state of a generator between yield calls?
Answer: Option A
Explanation: Generators maintain their local variables and execution position between yield calls.
Q20
How are generators different from iterator objects?
Answer: Option A
Explanation: Generators are a convenient way to create iterators using functions with yield, while iterators require implementing __iter__ and __next__ methods.