Introduction to Iterators
Lesson Introduction
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.
What is an Iterator?
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:
- Returning the data from a stream or container one item at a time.
- Keeping track of the current and visited items.
How to Create an Iterator in Python: Part 1
To create an iterator, you need a class that implements __iter__() and __next__(). Let’s look at a Counter class to understand this better:
__init__()initializes the counter withlowandhigh.self.currentis initialized tolowand will keep track of the current value.self.highis set to the upper bound of the counter.
__iter__()returns the iterator object itself, which allows theCounterinstance to be used directly in aforloop or with other iterator contexts.
How to Create an Iterator in Python: Part 2
Continuing with the Counter class:
__next__()is responsible for returning the next value in the iteration:- It first checks if
self.currenthas surpassedself.high. If so, it raises aStopIterationexception, signaling that the iteration is complete. - Otherwise, it increments
self.currentby 1 and then returns the previous value (i.e.,self.current - 1).
- It first checks if
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.
