Sobes.tech
Junior — Middle

What data types or objects support the iteration protocol?

sobes.tech AI

Answer from AI

In Python, the iteration protocol is supported by objects that implement the __iter__() method or the __getitem__() method with sequential indices. Such objects include:

  • Built-in collections: lists (list), tuples (tuple), sets (set), dictionaries (dict), strings (str).
  • Generators and iterators created using functions with yield.
  • User-defined classes that implement the __iter__() method.

Example of a custom iterator:

class Count:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

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

for number in Count(1, 5):
    print(number)

This code will output numbers from 1 to 5, demonstrating the iteration protocol.