python
iterator
iterable
programming
python-tutorial

What is the difference between iterator and iterable and how to use them?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

An essential part of Python and other programming languages is the concept of iteration, which allows for the sequential access of elements within a collection, such as lists, tuples, dictionaries, etc. Understanding the concepts of iterables and iterators is crucial for implementing effective iteration in your code. In this article, we will delve into the differences between iterables and iterators, how they function, and their applications.

Iterables vs. Iterators

Iterable

An iterable is an object that can return an iterator. Iterables are any Python objects capable of returning their elements one at a time, allowing them to be looped over in a for loop. Some common examples of iterables include lists, tuples, strings, and dictionaries.

To determine if an object is iterable, it must implement the __iter__ method, or alternatively, the __getitem__ method, which allows iteration over its elements.

Iterator

An iterator is an object that facilitates iteration over an iterable. An iterator in Python implements two primary methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, allowing its use in for loops and other contexts requiring an iterable. The __next__() method, on the other hand, returns the next item in the sequence. If no more items are available, a StopIteration exception is raised.

Key Differences Summed Up

Below is a table summarizing the key differences between iterables and iterators:

ConceptIterableIterator
DefinitionAn object capable of returning an iterator.An object used to iterate over an iterable.
MethodsRequires __iter__() or __getitem__()Requires __iter__() and __next__()
UsageUsed in constructs like for loops.Used to fetch elements one at a time.
StateDoes not maintain iteration state.Maintains iteration state.
ExamplesLists, Tuples, Dictionaries, Strings, etc.Objects returned by iter([1, 2, 3]), etc.

Using Iterables and Iterators

Using an Iterable

Let's consider a list as an example of an iterable:

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

In the above code, fruits is an iterable, which means we can loop over it using a for loop.

Using an Iterator

To demonstrate the use of an iterator, we manually obtain an iterator from an iterable and use the next() function:

python
1fruits = ["apple", "banana", "cherry"]
2fruit_iterator = iter(fruits)  # Convert the iterable into an iterator
3
4print(next(fruit_iterator))  # Output: apple
5print(next(fruit_iterator))  # Output: banana
6print(next(fruit_iterator))  # Output: cherry
7# Any further call to next(fruit_iterator) would raise a StopIteration exception

In the above example, fruit_iterator is an iterator obtained from the iterable fruits. The next() function is used to iterate over the elements manually. When all elements are exhausted, calling next() will result in a StopIteration exception.

Creating a Custom Iterator

Python allows you to create your own iterator by implementing the __iter__() and __next__() methods. Here's an example:

python
1class Countdown:
2    def __init__(self, start):
3        self.current = start
4
5    def __iter__(self):
6        return self
7
8    def __next__(self):
9        if self.current <= 0:
10            raise StopIteration
11        self.current -= 1
12        return self.current
13
14countdown = Countdown(3)
15for number in countdown:
16    print(number)  # Output: 2, 1, 0

In this code, Countdown is a custom iterator that decrements from a starting number down to zero.

Checking for Iterables and Iterators

To check if an object is iterable, you can use the collections.abc module:

python
1from collections.abc import Iterable
2
3is_iterable = isinstance([1, 2, 3], Iterable)
4print(is_iterable)  # Output: True

For checking if an object is an iterator:

python
1from collections.abc import Iterator
2
3is_iterator = isinstance(iter([]), Iterator)
4print(is_iterator)  # Output: True

Conclusion

Understanding the distinction between iterables and iterators is fundamental for grasping how Python handles iteration. Iterables provide the data over which we'll iterate, while iterators manage the state and logic for fetching new elements. Whether using Python's built-in iterable objects or custom iterator classes, the interplay between these two concepts forms the backbone of efficient data processing in Python.


Course illustration
Course illustration

All Rights Reserved.