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:

  1. Returning the data from a stream or container one item at a time.
  2. 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:

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        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.

How to Create an Iterator in Python: Part 2

Continuing with the Counter class:

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1
  • __next__() is responsible for returning the next value in the iteration:
    • It first checks if self.current has surpassed self.high. If so, it raises a StopIteration exception, signaling that the iteration is complete.
    • Otherwise, it increments 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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal