HomeInterview QuestionsWhat are Python generators and how are they used?

What are Python generators and how are they used?

🟢 Easy Conceptual Fresher level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

A generator is a special type of iterator that yields values one at a time and generates them on the fly, rather than computing all values upfront. It is defined using a function with the yield keyword or a generator expression. Generators are memory‑efficient for large data streams, allow lazy evaluation, and can maintain state between yields. They are commonly used for reading large files line by line, streaming data, or implementing infinite sequences. Example:

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

Iterating over countdown(5) produces 5,4,3,2,1 without storing the entire list.

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 on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500