HomeInterview QuestionsI am asking about Python generators. How do you us…

I am asking about Python generators. How do you use them? For example, how does the yield statement work?

🟢 Easy Conceptual Fresher level
20Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

A generator is a special type of iterator in Python that yields values one at a time, pausing its state between each yield. It is defined like a normal function but uses the yield keyword instead of return. When a generator function is called, it returns a generator object without executing the function body. Each call to next() on that object runs the function until it hits a yield, returns the yielded value, and suspends execution. Subsequent next() calls resume from that point.

Example:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for i in countdown(3):
    print(i)

Output: 3 2 1

Generators are memory‑efficient for large or infinite sequences, allow lazy evaluation, and can be used in for loops, comprehensions, or passed to functions like sum() or max().

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500