Generators Questions and Answers
Practice ModeShowing 10 of 25 questions
Q1
What is a generator in Python?
Answer: Option A
Explanation: Generators are functions that return an iterable generator object and use yield statements to produce a sequence of values lazily.
Q2
Which keyword is used to create a generator function?
Answer: Option A
Explanation: The yield keyword is used in generator functions to return values one at a time, pausing execution between calls.
Q3
What is the main advantage of using generators over lists?
Answer: Option A
Explanation: Generators are memory efficient because they generate values on-the-fly and don't store all values in memory at once.
Q4
How do you create a generator expression?
Answer: Option A
Explanation: Generator expressions use parentheses () instead of square brackets [] used for list comprehensions.
Q5
What happens when a generator function calls yield?
Answer: Option A
Explanation: When yield is called, the function state is saved and execution pauses, resuming from that point on the next call.
Q6
Which method is used to get the next value from a generator?
Answer: Option A
Explanation: The next() function is used to retrieve the next value from a generator object.
Q7
What exception is raised when a generator is exhausted?
Answer: Option A
Explanation: StopIteration exception is raised when a generator has no more values to yield.
Q8
Can a generator function have multiple yield statements?
Answer: Option A
Explanation: Generator functions can have multiple yield statements, and execution resumes from the last yield point.
Q9
What is the output of: (x*x for x in range(3))
Answer: Option A
Explanation: This generator expression creates squares of numbers 0, 1, 2 but needs to be consumed to see values.
Q10
How can you iterate through all values of a generator?
Answer: Option D
Explanation: Generators can be directly used in for loops, which automatically handle the StopIteration exception.