Welcome to your first lesson on iterators in Python! In this lesson, you will learn what an iterator is, why iterators are useful, and how to create and use them in Python. By the end, you'll understand how to use iterators to make your code efficient and easy to read.
An iterator is an object that allows you to traverse through a collection of elements, like a list or tuple. Think of an iterator like a sales clerk with an inventory list in a store, going item by item until every item is checked.
In Python, an iterator implements two methods: __iter__()
and __next__()
. The __iter__()
method returns the iterator object itself, and the __next__()
method returns the next element in the collection.
Iterators take responsibility for two main actions:
To create an iterator, you need a class that implements __iter__()
and __next__()
. Let’s look at a Counter
class to understand this better:
Python1class Counter: 2 def __init__(self, low, high): 3 self.current = low 4 self.high = high 5 6 def __iter__(self): 7 return self
__init__()
initializes the counter with low
and high
.
self.current
is initialized to low
and will keep track of the current value.self.high
is set to the upper bound of the counter.__iter__()
returns the iterator object itself, which allows the Counter
instance to be used directly in a for
loop or with other iterator contexts.Continuing with the Counter
class:
Python1class Counter: 2 def __init__(self, low, high): 3 self.current = low 4 self.high = high 5 6 def __iter__(self): 7 return self 8 9 def __next__(self): 10 if self.current > self.high: 11 raise StopIteration 12 else: 13 self.current += 1 14 return self.current - 1
__next__()
is responsible for returning the next value in the iteration:
self.current
has surpassed self.high
. If so, it raises a StopIteration
exception, signaling that the iteration is complete.self.current
by 1 and then returns the previous value (i.e., self.current - 1
).Short Reminder on Exceptions: Exceptions in Python are events that can alter the flow of a program. They occur when an error arises, and they can be caught and handled using try...except
blocks. The StopIteration
exception is a specific type of exception used to signal the end of an iteration.
To use an iterator, you typically use a for
loop. The loop calls __iter__()
and __next__()
behind the scenes. Here’s how to use our Counter
class:
Python1class Counter: 2 def __init__(self, low, high): 3 self.current = low 4 self.high = high 5 6 def __iter__(self): 7 return self 8 9 def __next__(self): 10 if self.current > self.high: 11 raise StopIteration 12 else: 13 self.current += 1 14 return self.current - 1 15 16def main(): 17 counter = Counter(1, 5) 18 19 for num in counter: 20 print(num) # 1, 2, 3, 4, 5 21 22if __name__ == "__main__": 23 main()
The for
loop calls __next__()
until it catches the StopIteration
exception.
Python provides several built-in iterators. Common examples include:
for
loop to traverse a list, tuple, or string, Python internally uses an iterator to iterate over the elements..values()
or .items()
.for
loop or methods like .readlines()
, Python employs an iterator to go through each line sequentially.In this lesson, you learned what an iterator is, and how to create and use one in Python. We used a Counter
class to understand __iter__()
and __next__()
. By creating a custom iterator, you control the logic for traversing any collection of elements. We also touched upon built-in iterators and how to handle exceptions in Python.
Now that you have learned the basics of iterators, it's time to practice. In the exercises, you will create your own iterators and use them to traverse and process data collections. Let's get started!