Python Medium technical 0 views 1 min read

In Python what are iterators?

Peer-reviewed by HireXTech Technical Panel • Updated for 2025/2026 hiring • Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

An iterator in Python is an object that represents a stream of data. It implements the Python Iterator Protocol, which consists of two core magic methods:

  1. __iter__(): Returns the iterator object itself.
  2. __next__(): Returns the next item from the sequence. When no elements remain, it raises the StopIteration exception.

### Custom Iterator Example:

class CountUpTo:
    def __init__(self, max_value):
        self.max_value = max_value
        self.current = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= self.max_value:
            val = self.current
            self.current += 1
            return val
        raise StopIteration

counter = CountUpTo(3)
for num in counter:
    print(num)  # Prints 1, 2, 3

### Iterable vs Iterator:

  • An Iterable is any object that can return an iterator via iter(obj) (e.g. lists, tuples, dicts, strings).
  • An Iterator is the stateful helper that actually produces values one at a time via next(it).

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?