Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Easy Python Patterns: The Iterator — Code nomad

3 min readDec 11, 2025

--

Press enter or click to view image in full size
Picture by Black ice: https://www.pexels.com/nl-nl/foto/wekker-liggend-op-veelkleurige-oppervlak-1314544/

Introduction

In Design Patterns, the Iterator is a way of traversing over a container, that is access each of the container’s elements. It is used as a convenient way to traverse over lists or arrays, but it could also be used to traverse over binary trees for example.

It looks like this:

A bit of explanation can be handy:

  1. An iterator basically has two methods: next() and hasNext()
  2. The next() method returns the next element in the container
  3. The hasNext() method returns a bool, true if a next element is available, false if there is no next element.

Implementation in Python

Like many modern languages, iterators are built into the language itself, lists and tuples for example can be iterated over. For our purpose we will build our own custom iterator, which just yields even numbers, up to a certain limit. You will see it will behave just like any other iterable type.

Since we want to return the type of the enclosing class, we need the following import:

--

--

The Code Nomad
The Code Nomad

Written by The Code Nomad

Fueled by a passion for code and music, with 25+ years in IT and a lifelong soundtrack playing in the background—that's what keeps me going.

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.