Python : Iterator, Iterable and Iteration explained with examples

In this article we will discuss what is Iterator, Iterable and Iterator in python with examples.


What is an Iterable?

Iterable is kind of object which is a collection of other elements. For example list and tuple are Iterables. It is similar to any collection class in Java or container class in C++. In Python when iter() function is called on an Iterable object then it returns an Iterator, which can be used to iterate over the elements inside Iterable.

In Python a class is called Iterable if it has overloaded the magic method __iter__() . This function must return an Iterator object.

What is an Iterator ?

Iterator is an object that enables us to iterate over the associated container or an Iterable object.

In Python a class is called Iterator if it has overloaded the magic method __next__(). This function must return one element at a given time and then increments the internal pointer to next.

What is Iteration ?

Iteration is a process of iterating over all the elements of an Iterable using Iterator object. In python we can do iteration using for loops or while loop.

Let’s understand by some examples,

Iterate over list (Iterable) using Iterator

Suppose we have a list of Numbers i.e.

# List of Numbers
listOfNum = [11, 12, 13, 14, 15, 16]

List in python is an Iterable object because it has overloaded the __iter__() function, which returns an Iterator. To get the Iterator object from a Iterable object we need to call iter() function. Let’s get the Iterator object from list i.e.

# get the Iterator of list
listIterator = iter(listOfNum)

It return a object list_iterator which is basically an Iterator because it has overloaded __next__() function. You can also check the type of Iterator returned i.e.

# Check type of iterator returned by list
print(type(listIterator))

Output:

<class 'list_iterator'>

Now let’s use this iterator object to iterate over the contents of list i.e.

# get the Iterator of list
listIterator = iter(listOfNum)

# Itearte over the all elements in list using iterator
while True:
    try:
        # Get next element from list using iterator object
        elem = next(listIterator)
        # Print the element
        print(elem)
    except StopIteration:
        break

Output:

11
12
13
14
15
16

Here, we called next() function on Iterator object again & again to iterate over all its elements.

How did it worked ?

To get the next value of the Iterable, call next() function on its iterator object. It will return the next value of the Iterable. Keep on calling this next() function to get all elements of iterable one by one. When iterator reaches the end of elements in iterable then it will throw StopIteration error.

What’s equivalent to hasnext() in Python Iterators ?

As explained above next() function is equivalent to the hasnext() in Python. It is used to get the next value from the Iterable.

Iterate over an Iterable (list) using for loop

Python has a magical for loop that internally uses Iterator to iterate over the Iterable object. For example we can iterate over the elements in list (Iterable) using for loop too i.e.

# Iterate over the Iterable (list) using for loop
for elem in listOfNum:
    print(elem)

Output:

11
12
13
14
15
16

for loop internally does the same thing, it fetches the Iterator from Iterable and then uses it to iterate over the elements in Iterable. But it provides a short hand form, we don’t need to write big while loop and catch StopIteration error our self, it does all that internally for us.

Similarly we can iterate over other Iterables too like list, tuple and other custom Iterators.

Some Important Points:

iter() Function in Python

When iter() function is called then it calls the __iter__() function on the passed object and returns the value returned by it. Basically a class that has overloaded __iter__() function is called Iterable and it is expected that it will return an Iterator object.

next() Function in Python

When next() function is called then it calls the __next__() function on the passed object and returns the value returned by it. Basically Iterator objects overloads the __next__() function and it returns the next value from the associated Iterable object.

In Next article we will discuss how to make our custom class Iterable and write separate Iterator class for Iterating over the elements in our Iterable class.

Complete example is as follows:

def main():

    # List of Numbers
    listOfNum = [11, 12, 13, 14, 15, 16]

    print('*** Iterate over the list using Iterator ***')

    # get the Iterator of list
    listIterator = iter(listOfNum)

    # Check type of iterator returned by list
    print(type(listIterator))

    # Itearte over the all elements in list using iterator
    while True:
        try:
            # Get next element from list using iterator object
            elem = next(listIterator)
            # Print the element
            print(elem)
        except StopIteration:
            break

    print('*** Iterate over the list using for loop ***')

    # Iterate over the Iterable (list) using for loop
    for elem in listOfNum:
        print(elem)

if __name__ == '__main__':
  main()

Output:

*** Iterate over the list using Iterator ***
<class 'list_iterator'>
11
12
13
14
15
16
*** Iterate over the list using for loop ***
11
12
13
14
15
16

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top