Iterable vs Iterator in Python – What is the difference?

Python Iterable Vs Iterator

In this tutorial, we are going to discuss the difference between iterable vs iterator in Python.


Understanding an iterable vs iterator

Anything which we can loop or iterate over is called an iterable in Python. When we pass an iterable object into the iter() function in Python, it returns an iterator.

In Python, an iterator is an object which is obtained from an iterable object by passing it to the iter() function. An iterator holds a countable number of values that can be iterated upon. An iterator is used to iterate over the iterable objects like lists, strings, tuples, etc. in Python. On the iteration of an iterator, it returns each element one by one.

NOTE: Every iterable object in Python is not an iterator but every iterator is iterable.

Iterables in Python

In Python, there are five well-known iterable objects. Let’s discuss them one by one.

1. List

A list is one of the most commonly used iterable objects in Python. It stores the data elements in an ordered manner. Let’s create a Python list and iterate it over.

# Create a Python list
list = ["JournalDev", "AskPython", "LinuxforDevices"]
print("This is a Python list:")
print(list)

# Iterate through the Python list
# using a for loop
print("Iterating a Python list:")
for element in list:
    print(element)

Output:

This is a Python list: 
['JournalDev', 'AskPython', 'LinuxforDevices'] 
Iterating a Python list: 
JournalDev 
AskPython 
LinuxforDevices

2. Tuple

A tuple is another commonly used iterable object in Python. Like a Python list, it also stores the data elements in an ordered manner. But the only key difference between a tuple and a list is- A tuple is an immutable object whereas a list is a mutable object in Python. Let’s create a Python tuple and iterate it over.

# Create a Python tuple
tuple = ('C', 'C++', 'Python', 'Java')
print("This is a Python tuple:")
print(tuple)

# Iterate through the Python tuple
# using a for loop
print("Iterating a Python tuple:")
for element in tuple:
    print(element)

Output:

This is a Python tuple: 
('C', 'C++', 'Python', 'Java') 
Iterating a Python tuple: 
C 
C++ 
Python 
Java

3. String

A string is also one of the most frequently used iterable objects in Python. Anything enclosed in single, double, or triple quotes is called a string in Python. It can either be a single line string or a multi-line string. Let’s create a Python string and iterate it over.

# Create a Python string
string = "PYTHON"
print("This is a Python string: " + string)

# Iterate through the Python string
# using a for loop
print("Iterating a Python string:")
for element in string:
    print(element)

Output:

This is a Python string: PYTHON
Iterating a Python string: 
P
Y 
T
H
O
N

4. Set

A set is again a very famous iterable object in Python. It is similar to a list and a tuple in Python but the only key difference is- A set does not allow duplicate elements inside it. Let’s create a Python set and iterate it over.

# Create a Python set
set = {"Go", "Dart", "Python", "Go"}
print("This is a Python set:")
print(set)

# Iterate through the Python set
# using a for loop
print("Iterating a Python set:")
for element in set:
    print(element)

Output:

This is a Python set: 
{'Go', 'Python', 'Dart'} 
Iterating a Python set: 
Go 
Python 
Dart

5. Dictionary

A dictionary is another very widely used iterable object in Python. It is used to store the data in the key: value format where the key must be a single-valued entity while its corresponding value can be either a single-valued entity or a multi-valued entity. Let’s create a Python dictionary and iterate it over.

# Create a Python dictionary
dict = {'py': 'PYTHON', 'mat': 'MATLAB', 'cpp': 'C++'}
print("This is a Python dictionary:")
print(dict)

# Iterate through the Python dictionary
# using a for loop
print("Iterating a Python dictionary:")
for key in dict:
    print(key + '-' + dict[key])

Output:

This is a Python dictionary: 
{'py': 'PYTHON', 'mat': 'MATLAB', 'cpp': 'C++'} 
Iterating a Python dictionary: 
py-PYTHON 
mat-MATLAB 
cpp-C++

Iterators in Python

When we create an object of the iterator class in Python, technically two methods get associated with it. These two methods belong to the iterator class and are collectively known as the iterator protocol.

Method 1: __iter__()

In Python, when we try to create an iterator object by passing an iterable object to the iter() function, the __iter__() method is invoked automatically. It is used to initialize an iterator object from the iterable object. This method returns an iterator object which can be used to iterate over the iterable objects like lists, tuples, dictionaries, etc.

Method 2: __next__()

In Python, when we try to iterate over the iterable objects the __next__() method is invoked automatically. It is used to iterate through all the elements of the iterator object. It returns the next element or value of the iterable object when applied to its iterator. It plays a very crucial role in stopping the iteration of the iterable objects by raising the StopIteration Exception when there is no item or element left in the iterable object to be returned by the __next__() method.

How to convert iterables ➔ iterators?

In Python, we can easily convert an iterable object like lists, tuples, sets, etc. to an iterator object simply by using the iterable object to the iter() function which in turn invokes the __iter__() method on the iterable object which is passed to the iter() function.

Let’s create an iterator object from an iterable object in Python and analyze the working of the __iter__() and __next__() methods of the iterator class.

# Create an iterable object
# here it's a Python list
iterable_obj = ['HTML', 'CSS', 'JAVA SCRIPT']
print(type(iterable_obj))
print(iterable_obj)

# Create an iterator object
# from the above iterable object (Python list)
# using the __iter__() method
iterator_obj = iterable_obj.__iter__()
print(type(iterator_obj))

# Iterate through the iterable object
# using its iterator object & the __next__() method
print(iterator_obj.__next__())
print(iterator_obj.__next__())
print(iterator_obj.__next__())

# Raise the StopIteration Exception
print(iterator_obj.__next__())

Output:

Output Iterator Object Creation
Output: iterator object creation

In the above Python code, we have created an iterable object (a Python list), converted it to an iterator object using the __iter__() method, accessed the elements of the iterable object using the __next__() method, and analyzed how the StopIteration Exception is raised by the __next__() method when it is called to access the next element of the iterable object but there are no elements left in the iterable object.

Using the for loop to iterate over the iterable object

We have seen the above examples of iterable objects, the for loop is widely used to iterate through the elements of the iterable object in Python. Let’s analyze the working of this for loop for iterators through Python code.

# Create an iterable object here it's a Python tuple
iterable = ('macOS', 'Linux', 'Windows')
print(type(iterable))
print(iterable)

# Iterate through the iterable object using a for loop
print("Iteration using for loop:")
for item in iterable:
    print(item)

# Analyze the implemention of for loop to iterate through the elements of
# the iterable object (Python tuple) using an infinite while loop and iterator protocol
def for_loop(iterable):
    # Create an iterator object from the passed iterable object
    # using the iter() function
    iterator = iter(iterable)

    # Run an infinite while loop
    while True:
        try:
            # Access the each element of the iterable object
            # using the next() function
            print(next(iterator))
        except StopIteration:
            # If the StopIteration Exception is raised
            # by the next() function break the while loop
            break

# Driver Code to check the implementation of the for_loop() function
print("Iteration using for_loop function:")
for_loop(iterable)

Output:

<class 'tuple'> 
('macOS', 'Linux', 'Windows') 
Iteration using for loop: 
macOS 
Linux 
Windows 
Iteration using for_loop function: 
macOS 
Linux 
Windows

From the above Python code, we have understood that a for loop to iterate over the elements of an iterable object is actually implemented through an infinite while loop. When we use a for loop to iterate over the iterable object, first an iterator object is created calling the iter() function, then an infinite while loop is run inside which the next() function is used to access the next element of the iterable object and the iteration is stopped when the StopIteration Exception is raised by the next() function as the elements of the iterable object gets exhausted.

Conclusion

In this tutorial, we have learned the following things.

  1. Difference between an iterable object and an iterator object in Python
  2. The iterator protocol i.e. __iter__() and __next__() methods of the iterator class
  3. Conversion of an iterable object into an iterator object
  4. Working of for loop to iterate over the elements of the iterable object