Sobes.tech
Junior — Middle

What is the role and main functions of an iterator in Python?

sobes.tech AI

Answer from AI

An iterator in Python is an object that implements the __next__() method and returns the next element of a sequence each time it is called. The main role of an iterator is to provide sequential access to the elements of a collection without needing to know the internal structure of that collection.

Main functions of an iterator:

  • Allows iterating over elements of collections (lists, tuples, dictionaries, etc.) in for loops.
  • Supports lazy loading of data, which saves memory.
  • Provides a unified interface for traversing different data types.

Example of creating a custom iterator:

class CountUpTo:
    def __init__(self, max):
        self.max = max
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.max:
            raise StopIteration
        self.current += 1
        return self.current

counter = CountUpTo(3)
for number in counter:
    print(number)  # Will output 1, 2, 3