Vidyalelo
Python · Q6

Generators and Iterators

Programming · Python · question 6

Q6

How are values produced in a generator function?

A.
Using the yield keyword
Answer
B.
Using the return keyword
C.
Using the print() function
D.
Using the generate keyword

Answer: Option A

Solution

Answer: Option A
Solution:
The correct answer is Option A: Using the yield keyword.
Values are produced in a generator function using the yield keyword. When a generator function encounters a yield statement, it temporarily suspends its execution and returns the yielded value. Subsequent calls to the generator function continue execution from where it was previously suspended, allowing it to generate values lazily, one at a time, as needed. This mechanism enables generators to efficiently handle large datasets or infinite sequences without loading all values into memory at once.