Sobes.tech
Junior

What is the difference between an iterator and an iterable object?

sobes.tech AI

Answer from AI

An iterable object is an object from which an iterator can be obtained. It implements the __iter__() method, which returns an iterator.

An iterator is an object that provides access to the elements of a collection one at a time. It implements the __iter__() and __next__() methods. The __next__() method returns the next element in the iteration or raises a StopIteration exception when exhausted.

# Example of an iterable object (list)
my_list = [1, 2, 3]

# Getting an iterator from an iterable object
my_iterator = iter(my_list) # Calls my_list.__iter__()

# Using the iterator to get elements
print(next(my_iterator)) # Calls my_iterator.__next__()
print(next(my_iterator))
print(next(my_iterator))

# When trying to get the next element after exhaustion
try:
    print(next(my_iterator))
except StopIteration:
    print("Iteration finished")

Key difference: an iterable object provides an iterator, and an iterator provides elements.

Comparison:

Characteristic Iterable Object Iterator
Implements method __iter__() __iter__(), __next__()
Action Returns an iterator Returns the next element
State Contains data Contains current position
Reusability Multiple iterators can be obtained Single-use only