LeetCampus
Interview Question

What are Iterators in Python?

July 24, 2025
0 views
Difficulty: Medium
Popularity: Common
Share on

Question Explanation

Iterators in Python are a fundamental concept that allows for efficient looping through collections like lists, tuples, and dictionaries. Interviewers often ask about iterators to assess a candidate's understanding of Python's data handling capabilities and their ability to work with iterable objects. Knowing how iterators function is essential for writing clean and efficient code, especially when managing large datasets or streams of data. Iterators enable lazy evaluation, meaning that values are generated only as needed, which can significantly reduce memory usage. Common misconceptions include confusing iterators with lists; while a list is a collection of items, an iterator is an object that keeps track of its current position in that collection. This understanding is crucial, as it connects to other Python concepts such as generators and context managers. Mastery of iterators also showcases a developer's ability to write more Pythonic code, emphasizing readability and efficiency. Overall, iterators are integral to Python programming, making them a common topic in technical interviews.

Sample Answers

Example 1: Basic Definition and Use

In Python, an iterator is an object that implements two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, while __next__() returns the next value from the sequence. Once all values are exhausted, __next__() raises a StopIteration exception. For example, consider the following code:

class MyIterator:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current - 1
        else:
            raise StopIteration

for number in MyIterator(5):
    print(number)

This code defines a simple iterator that counts from 0 to a specified limit. Understanding this basic structure is crucial as it lays the groundwork for more complex iterators and can be applied in various scenarios in Python programming.

Example 2: Using Built-in Iterators

Python provides built-in iterators such as lists, tuples, and dictionaries. When you loop over these collections, Python automatically creates an iterator for you. For instance, when using a list:

my_list = [1, 2, 3]
iterator = iter(my_list)

print(next(iterator))  # Output: 1
print(next(iterator))  # Output: 2
print(next(iterator))  # Output: 3

Once all elements are accessed, calling next(iterator) raises a StopIteration exception. This automatic iterator handling simplifies code and enhances readability, making it easier to traverse through data structures without the need for manual index management. Understanding how built-in iterators function is vital for leveraging Python's capabilities effectively.

Example 3: Generators as Iterators

Generators are a powerful feature in Python that simplify the creation of iterators. A generator is defined using a function with the yield statement, which allows it to return values one at a time and maintain its state between calls. Here’s an example:

def count_up_to(limit):
    count = 1
    while count <= limit:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)

This generator function yields numbers from 1 to the specified limit. Unlike traditional iterators, generators are more memory-efficient since they yield items one at a time rather than storing the entire list in memory. This understanding of generators is crucial for writing efficient, scalable applications in Python.

Keywords

PythonIteratorsData StructuresProgrammingEfficiency

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions