Loading

Quipoin Menu

Learn • Practice • Grow

python / Iterators and Generators
interview

Q1. What is an iterator in Python?
An iterator is an object that implements the iterator protocol: __iter__() returns itself, __next__() returns the next item or raises StopIteration.
Iterators are used to loop over collections lazily.
Many built-in types (list, tuple) are iterable but not iterators; they return iterators via iter().

Q2. What is a generator in Python?
A generator is a special function that yields values one at a time using the yield keyword, instead of return. It returns a generator iterator that can be iterated over.
Generators are memory-efficient for large data sets.
Example:
def squares(n):
    for i in range(n):
        yield i*i

Q3. What is the difference between generator and list?
A generator produces values on the fly and does not store them in memory, making it suitable for large sequences.
A list stores all elements in memory.
Generators are single-use (once exhausted, you need to recreate).
Lists can be accessed multiple times.

Q4. How do you create a generator expression?
Similar to list comprehension but with parentheses instead of brackets.
Example:
gen = (x**2 for x in range(10))
This creates a generator, not a list.

Q5. What is the purpose of yield from?
yield from is used to delegate part of a generator's operations to another iterator. It simplifies nested generators.
Example:
def chain(*iterables):
    for it in iterables:
        yield from it