Python Iterators
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python Iterators

Kishore V


Python Iterators

An iterator is an object that lets you traverse through a sequence of values one element at a time. Instead of holding all values in memory at once, an iterator produces values on demand.

In Python, an iterator follows the iterator protocol, which means it implements two special methods:

  • __iter__() → returns the iterator object
  • __next__() → returns the next value from the sequence

Iterator vs Iterable

  • Iterable: An object you can loop over (list, tuple, string, set, dictionary, etc.)
  • Iterator: The object that actually keeps track of iteration and returns values one by one

You can get an iterator from any iterable using the built-in iter() function.

Getting an Iterator from an Iterable

Example: Iterator from a List

apple orange mango

Example: Iterator from a String

Strings are also iterable, character by character.

p y t

Looping Through an Iterator

You usually don’t call next() manually. A for loop does this automatically behind the scenes.

Example: Looping Through a Set

green red blue

Example: Looping Through a String

c o d e

Note: Internally, the for loop:

  • Creates an iterator using iter()
  • Calls next() repeatedly
  • Stops when StopIteration is raised

Creating Your Own Iterator

To create a custom iterator, define a class that implements:

  • __iter__()
  • __next__()

Example: Custom Iterator (Even Numbers)

This iterator generates even numbers starting from 2.

2 4 6 8

Preventing Infinite Iteration – StopIteration

Without a stopping condition, an iterator can run forever. To stop iteration, raise the StopIteration exception inside __next__().

Example: Iterator with a Stop Condition

This iterator generates square numbers up to a limit.

1 4 9 16 25

Our website uses cookies to enhance your experience. Learn More
Accept !