Writing an iterator class takes a lot of code. A generator gives the same result with a normal-looking function: replace return (or print) with yield. Generators produce values on demand, so they can handle huge or even endless sequences using very little memory.
Generator functions
Calling a generator function does not run its body; it returns a generator object.
Each next() resumes the body from where it paused, up to the next yield.
When the function finishes (or reaches return), the generator raises StopIteration.
yield is a keyword, so yield i and yield(i) mean the same.
Generators are used up
A generator is an iterator, so it can be looped over only once. To loop again, call the generator function again to get a new generator, or store the values in a list.
Generator expressions
A generator expression looks like a list comprehension in round brackets: (x * x for x in range(10)). It builds a generator instead of a list. When it is the only argument of a function, the extra brackets can be dropped: sum(x * x for x in range(10)).
List
Generator
Created with
[...], list(...), list comprehension
Generator function (yield) or generator expression (...)
Values
All computed and stored at once
Computed one at a time, on demand
Memory
Grows with the number of items
Small and constant
Reuse
Can be looped over many times; supports len() and indexing
Used up after one pass; no len() or indexing
Best for
Data needed several times, or random access
Large or endless streams processed once
Key takeaways
yield turns a function into a generator function.
Calling it returns a generator; next() runs it to the next yield.
Generator expressions use ( ... ) and are evaluated lazily.
Generators save memory but can be used only once.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a generator function fibonacci(n) that yields the first n Fibonacci numbers, and show how to print them and how to get them as a list.
Show worked answer
def fibonacci(n): a, b = 0, 1 then for _ in range(n): yield a followed by a, b = b, a + b. Print: for f in fibonacci(7): print(f, end=" ") gives 0 1 1 2 3 5 8. List: list(fibonacci(7)) gives [0, 1, 1, 2, 3, 5, 8]. Each value is produced only when requested, and only a and b are kept in memory.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/python-advanced-concepts/generators/ to read this page.