Iterators in Python are a very important concept that provides a unified way to access elements in a collection without worrying about the specific implementation details of the collection.
Definition
An iterator is an object that remembers the traversal position. It starts accessing from the first element of the collection and continues until all elements have been accessed. An iterator can only traverse forward and cannot go backward.
Core Concepts
Iterator Protocol:
-
An object must implement the __iter__() method, returning the iterator itself.
-
It must implement the __next__() method, returning the next element in the sequence; if there are no more elements, it raises a StopIteration exception.
Iterable Objects:
-
Any object that implements the __iter__() method (such as lists, tuples, dictionaries, sets, strings, etc.).
-
Can be traversed using a for loop, as for automatically calls the iter() method to get the iterator.
Iterator vs Iterable Object
-
Iterable Object: A data structure that contains elements (such as list, tuple, dict) that can generate an iterator.
-
Iterator: A specific tool responsible for traversing the iterable object, returning the next value each time next() is called.
Creating an Iterator
To create an iterator object, you need to implement the __iter__() and __next__() methods in a class. Below is a simple iterator example that returns integers from 1 to a specified number:
class MyNumbers: def __init__(self, limit): self.limit = limit self.current = 0
def __iter__(self): return self
def __next__(self): if self.current < self.limit: self.current += 1 return self.current else: raise StopIteration
# Using the custom iterator
my_iter = MyNumbers(5)
for num in my_iter: print(num)
Code Explanation:
-
__init__() method initializes the initial state of the iterator, setting the limit and the current number.
-
__iter__() method returns the iterator object itself, as required by the iterator protocol.
-
__next__() method returns the next value of the iterator. When the limit is reached, it raises a StopIteration exception to terminate the iteration.
Using the built-in iter() function: Converts iterable objects (like lists, tuples, strings, etc.) into iterators.
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
Built-in Iterators
Python has many built-in functions that can return iterators, such as range(), enumerate(), zip(), etc.
range() Example
for i in range(5): print(i)
enumerate() Example
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits): print(index, fruit)
zip() Example
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages): print(name, age)
Advantages
-
Memory Efficient: Iterators are lazily evaluated, meaning they generate one value at a time instead of generating all values at once, thus saving a lot of memory.
-
Versatility: All objects that support iterators can be processed using for loops, map(), filter(), and other tools.
-
Infinite Sequences: You can create an iterator that generates an infinite sequence, such as an iterator that generates all positive integers.