Python Iterators

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

Output:

apple
orange
mango
Try it Yourself

Example: Iterator from a String

Strings are also iterable, character by character.

Output:

p
y
t
Try it Yourself

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

Output:

red
green
blue
Try it Yourself

Example: Looping Through a String

Output:

c
o
d
e
Try it Yourself

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.

Output:

2
4
6
8
Try it Yourself

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.

Output:

1
4
9
16
25
Try it Yourself

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