Skip to content

Iterators and Generators

Iterators and generators are important memory-saving tools in Python. They allow you to work with sequences of data (of any size) without loading everything into memory at once. Instead, each member of the iterable is processed individually. This is especially useful when dealing with large datasets or streams of data.

What is an Iterable?

An iterable is any Python object that can return its members one at a time, allowing it to be iterated over using a loop (see For Loops and While Loops). The order in which iterables are iterated over depends on their type. For example:

Tip

Not everything in Python is iterable. For example, integers and floats are not iterable. If you try to iterate over them, you'll get a TypeError exception.

You can check if an object is iterable by using the isinstance() function with the collections.abc.Iterable class.

Checking if Iterable
1
2
3
4
5
6
7
from collections.abc import Iterable
def is_iterable(obj):
    return isinstance(obj, Iterable)

print(is_iterable([1, 2, 3]))
print(is_iterable("Hello"))
print(is_iterable(42)) # (1)
  1. Integers are not iterable, so this will return False.

Would return:

True
True
False

What is an Iterator?

An iterator is any object that implements the iterator protocol, which consists of two methods:

  • __iter__(): Returns the iterator object itself.
  • __next__(): Returns the next value from the iterator. If there are no more items, it raises a StopIteration exception.