Yes, Python fully supports iteration.
Python provides robust support for iteration, making it a fundamental aspect of the language. Iteration allows you to access elements of a sequence (like lists, tuples, strings, etc.) one by one. This capability is largely facilitated through the iterator protocol, which relies on two core methods: __iter__()
and __next__()
.
How Iteration Works in Python
- Iterable: An object capable of returning its members one at a time. Common examples include lists, tuples, strings, dictionaries, and sets.
- Iterator: An object that produces successive items from the iterable. An iterator is created from an iterable using the
iter()
function. The iterator's__next__()
method retrieves the next item. When there are no more items,__next__()
raises aStopIteration
exception. - The
for
loop: Python'sfor
loop is a key mechanism for iteration. It automatically handles the process of obtaining an iterator from an iterable and repeatedly calling the iterator's__next__()
method until aStopIteration
exception is raised.
The Iterator Protocol
To support iteration, an object must adhere to the iterator protocol, which involves implementing the following methods:
__iter__()
: This method should return the iterator object itself. It is called at the beginning of a loop.__next__()
: This method should return the next value from the iterator. When there are no more values to return, it should raise aStopIteration
exception.
Example
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
# Attempting to call next() again will raise StopIteration
# print(next(my_iterator))
In this example, my_list
is an iterable. Calling iter(my_list)
returns an iterator object. Each call to next()
retrieves the next element.
Pythonic Iteration with for
Loops
The for
loop provides a cleaner and more Pythonic way to iterate:
my_list = [1, 2, 3]
for item in my_list:
print(item)
This loop automatically handles the iterator creation and exception handling.
Conclusion
Python's support for iteration is a cornerstone of the language's design, providing a flexible and efficient way to process sequences of data. The iterator protocol, along with features like for
loops, makes iteration easy and intuitive.