Understanding Python Iterators and Iterables

 

 

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() and next() 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 raises StopIteration to stop the loop.
  • We create an object counter = CountUpTo(5) and iterate over it using a for loop.

▶️ How to Run This Program

  1. Open a text editor (like VS Code, Sublime, or IDLE).
  2. Copy the above code into a file and save it as iterator_example.py.
  3. Open a terminal or command prompt and navigate to the file’s directory.
  4. Run the file using: python iterator_example.py
  5. You’ll see the numbers 1 through 5 printed on the screen.
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *