Master Python’s iteration protocol with clear examples
🔍 Introduction
In Python, understanding how iterables and iterators work is essential for writing efficient and clean code. These concepts are the backbone of for-loops, list comprehensions, and many powerful Python features.
🎯 Objective
The goal of this guide is to help you:
- Understand what an iterable and an iterator are.
- See the difference between them.
- Create your own iterator using a Python class.
- Learn how to use the
iter()
andnext()
functions.
💻 Python Code Example
# Custom iterator to return numbers up to a given limit
class CountUpTo:
def __init__(self, max_value):
self.max_value = max_value
self.current = 1
def __iter__(self):
return self # the iterator object
def __next__(self):
if self.current <= self.max_value:
num = self.current
self.current += 1
return num
else:
raise StopIteration
# Create an iterable object
counter = CountUpTo(5)
# Use the iterator
for number in counter:
print(number)
📘 Explanation
This program demonstrates a custom iterator class in Python:
CountUpTo
is a class that implements the iterator protocol using__iter__()
and__next__()
.- The
__iter__()
method returns the iterator object itself. - The
__next__()
method returns the next value until the maximum value is reached. It then raisesStopIteration
to stop the loop. - We create an object
counter = CountUpTo(5)
and iterate over it using afor
loop.
▶️ How to Run This Program
- Open a text editor (like VS Code, Sublime, or IDLE).
- Copy the above code into a file and save it as
iterator_example.py
. - Open a terminal or command prompt and navigate to the file’s directory.
- Run the file using:
python iterator_example.py
- You’ll see the numbers 1 through 5 printed on the screen.