In Python, an iterator is an object that allows you to traverse through all the elements in a collection (such as a list, tuple, or dictionary) one by one. This article will explain how to create and use iterators in Python, along with some examples to help you understand their functionality.
An iterator is an object that implements two methods:
StopIteration
exception to signal the end of iteration.To create an iterator, you need to define a class that implements both the __iter__()
and __next__()
methods. This class can then be used to iterate through a collection of data.
class MyIterator: def __init__(self, start, end): self.current = start self.end = end def __iter__(self): return self def __next__(self): if self.current <= self.end: self.current += 1 return self.current - 1 else: raise StopIteration # Using the custom iterator my_iter = MyIterator(1, 5) for number in my_iter: print(number)
In this example, we create a custom iterator class MyIterator
that takes a start and end value. The __next__()
method returns the next number in the sequence, and when the end is reached, it raises the StopIteration
exception to indicate that the iteration is complete.
1 2 3 4 5
Python provides several built-in iterators, and you can iterate over various types of collections like lists, tuples, and dictionaries directly without needing to create a custom iterator. These collections implement the __iter__()
and __next__()
methods automatically.
numbers = [10, 20, 30, 40, 50] numbers_iter = iter(numbers) # Using the iterator print(next(numbers_iter)) # Output: 10 print(next(numbers_iter)) # Output: 20 print(next(numbers_iter)) # Output: 30
In this example, we use the built-in iter()
function to create an iterator from the list numbers
. We can then use the next()
function to retrieve the next item from the list.
10 20 30
my_dict = {"a": 1, "b": 2, "c": 3} dict_iter = iter(my_dict) # Using the iterator print(next(dict_iter)) # Output: a print(next(dict_iter)) # Output: b print(next(dict_iter)) # Output: c
In this example, we iterate over the keys of the dictionary my_dict
using the iterator created with the iter()
function. By default, the iterator will return the keys.
a b c
StopIteration
ExceptionThe StopIteration
exception is a built-in exception that is raised when there are no more items to return from an iterator. It signals that the iteration is complete, and Python automatically handles this when using loops like for
.
my_iter = MyIterator(1, 3) print(next(my_iter)) # Output: 1 print(next(my_iter)) # Output: 2 print(next(my_iter)) # Output: 3 print(next(my_iter)) # Raises StopIteration
In this example, after iterating through all the values (1, 2, and 3), calling next()
again raises the StopIteration
exception because there are no more values left to iterate over.
In Python, you don't usually need to manually call the next()
function when using iterators in loops. The for
loop automatically handles the StopIteration
exception for you.
for
Loopfor number in MyIterator(1, 3): print(number)
This example demonstrates using the for
loop to iterate over the MyIterator
instance. The loop automatically stops when the iteration is complete.
1 2 3
Iterators are an essential part of Python, allowing you to traverse through collections of data in a memory-efficient and readable way. By implementing the __iter__()
and __next__()
methods, you can create custom iterators. Additionally, Python provides built-in iterators for common collections like lists and dictionaries. Understanding iterators and how to use them properly can help you write more efficient and Pythonic code.