Generators & Iterators Questions with Answers

30 practice questions on Generators & Iterators (Python) with answers and step-by-step solutions. Try 10 samples below, then practise all 30 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

r = reversed([1, 2, 3])
print(type(r).__name__ == "list", list(r))
  1. True [3, 2, 1]
  2. False [3, 2, 1]
  3. True [1, 2, 3]
  4. False [1, 2, 3]

Answer: B. False [3, 2, 1]

Explanation

reversed returns a reverse iterator object, not a list; converting it with list() gives [3, 2, 1].

Step-by-step solution

  1. reversed([1, 2, 3]) returns a reverse iterator object, not a list.
  2. type(r).__name__ is "list_reverseiterator", so the test against "list" is False.
  3. list(r) gives [3, 2, 1].
  4. The printed output is False [3, 2, 1], which is B.

Why the other options are wrong

  • A. The type is not list, so the first value is False.
  • C. The first value is False, and reversed gives [3, 2, 1], not [1, 2, 3].
  • D. Reversed reverses the order, so the list is [3, 2, 1].

Tip: reversed() returns an iterator; wrap it in list() to see the items.

Question 2Easy

What is the output?

nums = [1, 2, 3]
it = iter(nums)
print(next(it), next(it), next(it), next(it, "end"))
  1. 1 2 3 StopIteration
  2. 1 2 3 None
  3. 1 2 3 1
  4. 1 2 3 end

Answer: D. 1 2 3 end

Explanation

After the three items, the iterator is exhausted; next with a default returns "end" instead of raising StopIteration.

Step-by-step solution

  1. The iterator gives 1, 2 and 3 in turn to the first three next() calls.
  2. The fourth next(it, "end") finds no more items.
  3. Because a default was given, it returns "end" instead of raising StopIteration.
  4. The output is 1 2 3 end, which is option D.

Why the other options are wrong

  • A. The default stops the StopIteration error, so no exception is printed.
  • B. The default is returned, so the last value is "end", not None.
  • C. After the items, the iterator does not restart, so the last value is not 1.

Tip: next(it, default) gives the default instead of raising StopIteration when the iterator is empty.

Question 3Easy

What does the yield keyword do inside a function?

  1. It ends the function permanently, like return
  2. It stores the value in a global list
  3. It produces a value to the caller and pauses the function, keeping its local state for the next resume
  4. It runs the function in a separate thread

Answer: C. It produces a value to the caller and pauses the function, keeping its local state for the next resume

Explanation

A function containing yield becomes a generator function; each next() resumes it from the last yield with locals intact.

Step-by-step solution

  1. A function that contains yield is a generator function.
  2. Each yield sends a value to the caller and pauses the function.
  3. The local variables are kept, so the next next() call resumes from there.
  4. So the correct answer is option C.

Why the other options are wrong

  • A. Return ends the function for good; yield pauses it and can resume.
  • B. Yield does not store values in a global list; it hands each value to the caller.
  • D. Yield does not start a thread; the function runs in the same thread.

Tip: Yield makes a generator; the function resumes after the yield on the next next() call.

Question 4Easy

What is the output?

from itertools import islice, count
print(list(islice(count(5, 3), 4)))
  1. [3, 6, 9, 12]
  2. [5, 8, 11]
  3. [5, 6, 7, 8]
  4. [5, 8, 11, 14]

Answer: D. [5, 8, 11, 14]

Explanation

count(5, 3) produces 5, 8, 11, 14, ... endlessly; islice takes the first four values.

Step-by-step solution

  1. count(5, 3) starts at 5 and adds 3 each time: 5, 8, 11, 14, and so on.
  2. Islice takes the first four values.
  3. Those four values are 5, 8, 11 and 14.
  4. The output is [5, 8, 11, 14].

Why the other options are wrong

  • A. The start is 5, not 3, and the step is 3.
  • B. Islice takes four values, so there is a fourth item, 14.
  • C. The step is 3, so the values are not 5, 6, 7, 8.

Tip: count(start, step) is endless; islice gives the first few values.

Question 5Medium

What is the output?

from itertools import chain
print(list(chain([1, 2], "ab", (3,))))
  1. TypeError
  2. [[1, 2], 'ab', (3,)]
  3. [1, 2, 'ab', 3]
  4. [1, 2, 'a', 'b', 3]

Answer: D. [1, 2, 'a', 'b', 3]

Explanation

chain yields the items of each iterable in turn; a string is iterable, so "ab" contributes "a" and "b".

Step-by-step solution

  1. chain joins iterables one after another.
  2. Strings are iterable: 'ab' gives 'a','b'.
  3. Result [1,2,'a','b',3].

Why the other options are wrong

  • A. All arguments are iterable.
  • B. chain flattens one level.
  • C. The string is split into characters.

Tip: chain flattens one level.

Question 6Medium

Which method must a class define so that its instances can be used directly in a for loop (for x in obj)?

  1. __iter__, returning an iterator (or __getitem__ for the old sequence protocol)
  2. __next__ only
  3. __loop__
  4. __contains__

Answer: A. __iter__, returning an iterator (or __getitem__ for the old sequence protocol)

Explanation

for calls iter(obj), which uses __iter__ (falling back to __getitem__ with 0, 1, 2...). __next__ belongs on the iterator that __iter__ returns.

Step-by-step solution

  1. for x in obj calls iter(obj), which uses the class's __iter__ method.
  2. __iter__ must return an iterator; the iterator then needs __next__.
  3. The old protocol uses __getitem__ with 0, 1, 2... when __iter__ is missing.
  4. So the correct answer is A.

Why the other options are wrong

  • B. __next__ is needed on the iterator, but for loops start by calling iter on the object.
  • C. __loop__ is not a Python special method.
  • D. __contains__ is used by the in operator, not by a for loop.

Tip: Make __iter__ return self and define __next__ when you write a custom iterator.

Question 7Medium

What is the output?

d = {"a": 1, "b": 2}
it = iter(d.items())
k, v = next(it)
print(k, v, len(list(it)))
  1. a 1 1
  2. a 1 2
  3. ('a', 1) 1
  4. b 2 1

Answer: A. a 1 1

Explanation

Dicts keep insertion order, so the first item is ("a", 1), which is unpacked; one item remains.

Step-by-step solution

  1. Dict items come in insertion order, so the first item is ("a", 1).
  2. K, v = next(it) unpacks it, so k is "a" and v is 1.
  3. One item ("b", 2) is left, so len(list(it)) is 1.
  4. The output is a 1 1, which is option A.

Why the other options are wrong

  • B. The remaining count is 1, since only ("b", 2) is left.
  • C. The unpacking gives k = "a", so the tuple is not printed.
  • D. The first item is "a", not "b".

Tip: Dict items are in insertion order; unpacking an item gives its key and value.

Question 8Medium

What is the output?

m = map(int, ["1", "2", "3"])
print(sum(m), sum(m))
  1. 6 6
  2. 6 None
  3. TypeError
  4. 6 0

Answer: D. 6 0

Explanation

map returns a one-shot iterator; the first sum consumes it, so the second sum sees an empty iterator and returns 0.

Step-by-step solution

  1. Map returns a one-shot iterator over the three converted values, 1, 2 and 3.
  2. The first sum() reads all three values and returns 6.
  3. The second sum() sees the exhausted iterator and returns 0.
  4. The printed output is 6 0, which is option D.

Why the other options are wrong

  • A. The second sum reads nothing because the iterator was used up, so it is 0.
  • B. Sum returns 0 for an empty iterator, not None.
  • C. No TypeError happens; sum accepts an empty iterator.

Tip: Map, filter and zip are one-shot iterators; store the result in a list if you need to read it twice.

Question 9Hard

What is the output?

def g():
    try:
        yield 1
        yield 2
    finally:
        print("cleanup", end=" ")

for v in g():
    print(v, end=" ")
    break
print("end")
  1. 1 cleanup end
  2. 1 end cleanup
  3. 1 end
  4. 1 2 cleanup end

Answer: A. 1 cleanup end

Explanation

Breaking out of the for loop drops the last reference to the generator, which closes it immediately in CPython; close() raises GeneratorExit at the yield, so finally runs before "end".

Step-by-step solution

  1. The for loop gets 1 from the generator, prints it with a space, then breaks.
  2. When the loop stops, the generator is no longer referenced and is closed in CPython.
  3. Closing raises GeneratorExit at the yield, so the finally block prints cleanup.
  4. Then end is printed, giving 1 cleanup end.

Why the other options are wrong

  • B. The finally block runs when the generator is closed, before end is printed.
  • C. The cleanup line prints when the generator closes, so it appears in the output.
  • D. The break happens before 2 is yielded, so 2 is never printed.

Tip: A break out of a for loop drops the generator, which runs its finally block in CPython.

Question 10Hard

What is the output?

def gen():
    x = yield 1
    print("got", x, end=" ")
    yield 2

g = gen()
print(next(g), end=" ")
print(next(g))
  1. 1 got None 2
  2. 1 2
  3. 1 got 1 2
  4. 1 got 2 2

Answer: A. 1 got None 2

Explanation

Plain next() is equivalent to send(None), so the paused yield expression evaluates to None.

Step-by-step solution

  1. The first next runs to yield 1, which is printed with a space.
  2. The second next resumes the generator; the paused yield gives None, so x is None.
  3. The generator prints got None with a space, then yields 2.
  4. The printed output is 1 got None 2.

Why the other options are wrong

  • B. The got line is printed, so the output has more than 1 2.
  • C. Next sends None, so x is None, not 1.
  • D. X is None, not 2, and the 2 is only the yielded value.

Tip: next() resumes a paused generator with None for the yield expression.

Practise all 30 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Python topics · All topics