In programming, iteration plays a crucial role in traversing a sequence of elements. Python introduces two key concepts related to iteration: iterables and iterators.
What is an Iterable?
In Python, an iterable is an object that can be used in a for loop to access its elements one by one. It must implement the __iter__ method, which returns an iterator. Alternatively, an iterable may define a __getitem__ method that supports sequential indexing starting from zero and throws an IndexError when the indexes are no longer valid.
What is an Iterator?
An iterator is an object that provides a way to access elements of an iterable sequentially. It has a next() (in Python 2) or __next__ (in Python 3) method that returns the next element of the iterable. When there are no more elements left, the next() method raises a StopIteration exception.
Iteration Process
Iteration involves repeatedly calling the next() method of an iterator to fetch each element of an iterable. This process continues until the iterator raises a StopIteration exception. For example, when using a for loop in Python:
for element in iterable: # Process element
The for loop internally calls the next() method of the iterable's iterator to get the next element until StopIteration is raised.
The above is the detailed content of Iterables and Iterators in Python: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!