MCS-201 · Unit 15

Python Advanced Concepts

Section 3 of 5

Block 4 · Unit 15Python Advanced Concepts9 min · Section 3 of 5

15.3Generators

Covers IGNOU MCS-201 §15.4

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)).

ListGenerator
Created with[...], list(...), list comprehensionGenerator function (yield) or generator expression (...)
ValuesAll computed and stored at onceComputed one at a time, on demand
MemoryGrows with the number of itemsSmall and constant
ReuseCan be looped over many times; supports len() and indexingUsed up after one pass; no len() or indexing
Best forData needed several times, or random accessLarge 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 1 · multiple choice

What does calling a generator function return?

Show answer

Answer: C. A generator object

The body does not run until next() (or a loop) asks for a value.

Question 2 · multiple choice

Which creates a generator?

Show answer

Answer: B. (x * 2 for x in range(5))

Round brackets make a generator expression; square brackets make a list and braces make a set.

Question 3 · multiple choice

What does this program print?

Python · quiz_gen.py
def gen():
    yield 1
    yield 2

g = gen()
print(sum(g), sum(g))
Show answer

Answer: B. 3 0

The first sum consumes the generator; the second gets no values, giving 0.

Question 4 · multiple choice

What does this program print?

Python · quiz_yield.py
def letters():
    for ch in "abc":
        yield ch.upper()

print(list(letters()) + list(letters()))
Show answer

Answer: D. [‘A’, ‘B’, ‘C’, ‘A’, ‘B’, ‘C’]

Each call to letters() creates a new generator, so both lists are complete.

Question 5 · multiple choice

Why are generators memory-efficient?

Show answer

Answer: C. They produce one value at a time instead of storing all values together

Only the current state (local variables) is kept, not the whole sequence.

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.

↑ ↓ move↵ openTab switch type