LearnFrenzy
Sign in Take a free test

Python Programming · Topic 20 of 25

Iterators and Generators Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Iterators and Generators · Study material

Every for loop in Python runs on the iterator protocol: ask an iterable for an iterator, call next() until StopIteration. Generators make writing your own iterators almost effortless – a function with yield produces values one at a time, pausing in between, so it can handle huge files, endless streams and long pipelines in constant memory. Interviews ask the difference between an iterable and an iterator, how yield differs from return, why a generator works only once, and what yield from and send() do. This topic covers all of it, then 50 practice questions run on Python 3.

On this page

  • Iterables, iterators, iter(), next() and StopIteration
  • Writing an iterator class – and a reusable iterable
  • Generator functions and yield
  • Lazy evaluation and generator pipelines
  • yield from, return values and send()
  • Infinite generators with itertools

Iterables, iterators and the protocol

An iterable is anything you can loop over – list, str, dict, set, file, range. Calling iter() on it returns an iterator, an object with a __next__ method that returns the next item or raises StopIteration when there are none left. next(it, default) returns the default instead of raising. A for loop does exactly this behind the scenes. An iterator is also an iterable (its __iter__ returns itself), but it can be traversed only once.

fruits = ["apple", "mango", "kiwi"]       # an ITERABLE: can produce an iterator
it = iter(fruits)                         # an ITERATOR: remembers where it is
print(next(it), next(it), next(it))
print(next(it, "no more"))                # a default instead of StopIteration

# What a for loop really does:
it = iter(fruits)
while True:
    try:
        item = next(it)
    except StopIteration:
        break
    print("for-loop body:", item)

print(iter(it) is it, iter(fruits) is iter(fruits))   # iterators return themselves

Output

apple mango kiwi
no more
for-loop body: apple
for-loop body: mango
for-loop body: kiwi
True False

Writing an iterator class

An iterator class defines __iter__ (returning self) and __next__ (returning the next value or raising StopIteration). Because it keeps its position, it is exhausted after one pass. A class whose __iter__ returns a new iterator each time – an iterable – can be looped over again and again, like a list.

class Countdown:
    """An iterator: it has __next__ and returns itself from __iter__."""
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration       # signals the end
        self.current -= 1
        return self.current + 1

c = Countdown(3)
print(list(c))
print(list(c))                        # exhausted: an iterator is one-shot

class Range2:
    """An ITERABLE: each __iter__ call returns a fresh generator, so it can be looped many times."""
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        return iter(range(self.n, 0, -1))

r = Range2(3)
print(list(r), list(r))

Output

[3, 2, 1]
[]
[3, 2, 1] [3, 2, 1]

Generator functions and yield

A function containing yield is a generator function. Calling it runs none of its code; it returns a generator object. Each next() runs the body until the next yield, hands that value out and pauses, keeping all local variables. When the function ends, the generator raises StopIteration. return ends a function once; yield can produce many values.

def countdown(n):
    print("  (generator started)")
    while n > 0:
        yield n                  # hand a value out and PAUSE here
        n -= 1                   # resume from here on the next next()
    print("  (generator finished)")

gen = countdown(3)               # nothing runs yet – a generator object is created
print(type(gen).__name__)
print(next(gen))
print(next(gen))
for value in gen:                # the for loop continues where next() left off
    print(value)

Output

generator
  (generator started)
3
2
1
  (generator finished)

Lazy evaluation and pipelines

Generators compute values only when asked, so a generator over a million numbers uses a few hundred bytes. Chaining generators builds a pipeline in which each item flows through every stage before the next item is read – ideal for large files and data streams.

import sys

squares_list = [n * n for n in range(1_000_000)]   # all values stored now
squares_gen = (n * n for n in range(1_000_000))    # values produced on demand

print(sys.getsizeof(squares_gen) < 1000, sys.getsizeof(squares_list) > 1_000_000)
print(sum(squares_gen))

def read_numbers(lines):
    for line in lines:               # each stage handles one item at a time
        yield int(line)

def only_even(nums):
    for n in nums:
        if n % 2 == 0:
            yield n

pipeline = only_even(read_numbers(["4", "7", "10", "3", "8"]))
print(list(pipeline))

Output

True True
333332833333500000
[4, 10, 8]

yield from and generator return values

yield from iterable yields every item of another iterable or generator – handy for flattening and for splitting a generator into helpers. A return value inside a generator ends it and stores the value in the StopIteration exception's .value (and becomes the result of a yield from expression).

def flatten(items):
    for x in items:
        if isinstance(x, list):
            yield from flatten(x)     # delegate to another generator (recursively)
        else:
            yield x

print(list(flatten([1, [2, [3, 4]], [], 5])))

def chain(*iterables):
    for it in iterables:
        yield from it

print(list(chain("ab", [1, 2], range(3))))

def with_result():
    yield 1
    return "done"                     # a generator's return value travels in StopIteration

g = with_result()
next(g)
try:
    next(g)
except StopIteration as e:
    print("returned:", e.value)

Output

[1, 2, 3, 4, 5]
['a', 'b', 1, 2, 0, 1, 2]
returned: done

Infinite generators and itertools

A generator can run forever as long as the consumer takes only what it needs. The itertools module provides ready-made lazy tools: count(), cycle(), repeat(), islice() to take a slice of any iterator, takewhile() and dropwhile(), chain(), groupby() (groups neighbouring items), accumulate(), combinations() and more.

from itertools import count, cycle, islice, takewhile, chain, groupby

print(list(islice(count(10, 5), 4)))                  # 10, 15, 20, … – take only 4
print(list(islice(cycle("RGB"), 7)))                  # repeat forever, take 7
print(list(takewhile(lambda n: n < 40, count(1, 7)))) # stop at the first failure
print(list(chain([1, 2], (3,), "ab")))

def fibonacci():                      # an infinite generator is fine when consumed lazily
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(islice(fibonacci(), 10)))
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
print({k: list(g) for k, g in groupby(words, key=lambda w: w[0])})

Output

[10, 15, 20, 25]
['R', 'G', 'B', 'R', 'G', 'B', 'R']
[1, 8, 15, 22, 29, 36]
[1, 2, 3, 'a', 'b']
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

send(): generators as coroutines

gen.send(value) resumes a generator and makes the paused yield expression evaluate to that value, so data can flow in as well as out. A fresh generator must first be advanced to its first yield with next(gen) (or gen.send(None)).

def running_average():
    total = count = 0
    average = None
    while True:
        value = yield average        # yield gives a value out and receives one in
        total += value
        count += 1
        average = total / count

avg = running_average()
next(avg)                            # "prime" the generator: run to the first yield
for marks in [80, 90, 70]:
    print(avg.send(marks))

Output

80.0
85.0
80.0

Common mistakes

  • Looping over a generator twice – the second pass yields nothing.
  • Calling next() on a list – TypeError: call iter() first.
  • len() or indexing on a generator – TypeError.
  • return instead of yield inside a loop – the function stops after the first value.
  • __iter__ returning a list – TypeError: iter() returned non-iterator.
  • Letting StopIteration escape inside a generator – RuntimeError (PEP 479).
  • Forgetting that generators are lazy – variables they use are read when the values are produced.

Key points to remember

  • Iterable → iter() → iterator → next() … StopIteration.
  • Iterators are one-shot; iterables can create fresh iterators.
  • A yield in a function makes it a generator function.
  • Generators pause at yield and keep their local state.
  • Generators are lazy: memory stays constant.
  • yield from delegates; return value ends up in StopIteration.value.
  • Use islice / takewhile to consume infinite generators safely.

Frequently asked questions

Generator or list?

Use a generator when values are consumed once, in order, or when the data is large or endless. Use a list when you need len(), indexing, several passes or to keep the results.

Can a generator be restarted?

No. Call the generator function again to get a new generator.

Are zip, map, filter and enumerate generators?

They are lazy iterators (not generator objects, but they behave the same way): consumed once, values produced on demand.

Where can I learn more?

Read Python Generators and Python List Comprehensions in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links