What are Python generators and how are they used?
💡 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:
def countdown(n):
while n > 0:
yield n
n -= 1Iterating 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