Sobes.tech
Junior — Middle

How to distinguish an iterator from an object supporting the iteration protocol?

sobes.tech AI

Answer from AI

In Python, an iterator is an object that implements the __next__() method and the __iter__() method, where __iter__() returns the object itself. An object that supports the iteration protocol (an iterable object) implements only the __iter__() method, which returns an iterator.

In simpler terms:

  • An iterable object can be used in a for loop and can be converted into an iterator using iter(obj).
  • An iterator is an object that has a __next__() method returning the next element, and itself is an iterable (meaning iter(iterator) == iterator).

Example:

lst = [1, 2, 3]  # iterable object
it = iter(lst)    # iterator

print(hasattr(lst, '__iter__'))  # True
print(hasattr(lst, '__next__'))  # False

print(hasattr(it, '__iter__'))   # True
print(hasattr(it, '__next__'))   # True

print(next(it))  # 1

Thus, an iterator is an object that can be used to retrieve elements sequentially, and an iterable object is a container from which an iterator can be obtained.