Python Iterator vs Iterable
In Python, an Iterable is something that can be looped over or repeated. The Python iter() function returns an iterator when we supply an Iterable object to it.
By giving an Iterable object to the iter() function in Python, an iterator object can be created .An iterator stores a countable number of values that can be iterated upon. Iterating through Iterable objects in Python, such as lists, strings, tuples, etc. requires the usage of an iterator. It returns each element individually on an iterator's iteration.
Python Iterable
There are five well-known Iterable objects in Python. Let's go over each one individually.
1. List
One of the most popular Iterable objects in Python is a list. It arranges the data elements for storage. Let's build a Python list and loop through it.
# Create a Python list
#defining the values in the list
#with the help of indexing we will allocate the words in the list
list_1 = ["Jtp", "python", "JavaTpoint"]
print("This is a Python list: where the elements are indexed int the given list.")
#now printing the list values
print(list_1)
# Iterate through the Python list for the assigned values to get retrieved.
# using a for loop for accessing the elements.
print("Iterating a Python list and retrieving the values")
for i in list_1:
print(i)
Output:
This is a Python list: where the elements are indexed int the given list.
['Jtp', 'python', 'JavaTpoint']
Iterating a Python list and retrieving the values
Jtp
python
JavaTpoint
2. Tuple
Another often used Iterable object in Python is a tuple. It also stores the data items in an ordered fashion, much like a Python list. But in Python, the only major difference between a tuple and a list is that the former is an immutable object, while the latter is mutable. Create a Python tuple and run a loop across it.
# Create a Python tuple in the tuple we are assigning the values
# indexing the values and assigning the tuple values.
tuple_1 = ('c', 'c++' , 'Python', 'Java', 'JavaScript', '')
print("This is a Python tuple and iterating through the entire tuple :")
print(tuple_1)
# Iterate through the Python tuple and retrieving the values
# using a for loop and iterating the values and retrieving the values
print("Iterating a Python tuple and retrieving the values:")
for i in tuple_1:
print(i)
Output:
This is a Python tuple and iterating through the entire tuple :
('c', 'c++', 'Python', 'Java', 'javascript', '')
Iterating a Python tuple and retrieving the values:
c
c++
Python
Java
Javascript
3.String
One of the most often used Iterable objects in Python is a string. Python refers to everything that is single, double, or triple quoted as a string. It may be a multi-line string or a single line string. Let's build a Python string and loop through it.
# Create a Python string and assaiging the value
string = "PYTHON Is simple"
print("This is a Python string which contains the assaigned string value : " + string)
# Iterate through the Python string of the assaigned value
# using a for loop to retrieving the values
print("Iterating a Python string and retrieving the values using the for loop :")
for i in string:
print(i)
Output:
This is a Python string which contains the assaigned string value : PYTHON Is simple
Iterating a Python string and retrieving the values using the for loop :
P
Y
T
H
O
N
I
s
s
i
m
p
l
e
4. Set
Another well-known Iterable object in Python is the set. The only significant distinction between a set and a list or tuple in Python is that a set does not permit duplicate elements. Let's build a Python set and loop through it.
Program:
# Create a Python set and assaiging the values that are not duplicate.
set = {"react", "java", "c++", "Go"}
print("This is a Python set that are not containing the duplicate values:")
print(set)
# Iterate through the Python set for retrieving the values
# using a for loop
print("Iterating a Python set to retrieve the values:")
for i in set:
print(i)
Output:
This is a Python set that are not containing the duplicate values:
{'Go', 'c++', 'react', 'java'}
Iterating a Python set to retrieve the values:
Go
c++
react
java
#we will see what happens if we assaign the duplicate values to the set in python
Program:
# Create a Python set and assaiging the values that are not duplicate.
set = {"react", "java", "c++", "Go", "java" , "c++"}
print("This is a Python set that are not containing the duplicate values:")
#now we have assiagned the c++ and java for the second time and we will see what the output it prints.
print(set)
# Iterate through the Python set for retrieving the values
# using a for loop
print("Iterating a Python set to retrieve the values that are not duplicate:")
for i in set:
print(i)
Output:
This is a Python set that are not containing the duplicate values:
{'react', 'Go', 'java', 'c++'}
Iterating a Python set to retrieve the values:
react
Go
java
c++
So, this is how the python set is used that is mainly to delete the duplicate values from the given data sets.
5. Dictionary
Another often used Iterable object in Python is a dictionary. It is used to store data in a key: value format, where the key is required to be a single-valued entity and the value can either be a single-valued entity or a multi-valued entity. Let's build a Python dictionary and loop through it.
Program:
# Create a Python dictionary and assigining the values according to the key.
dict = {'p': 'PYTHON', 'm': 'Mac', 'c': 'C++'}
print("This is a Python dictionary for the key values pair:")
print(dict)
# Iterate through the Python dictionary for retriving the values based upon the keys
# using a for loop and retrieving the values.
print("Iterating a Python dictionary and retrieving the values in it:")
for key in dict:
print(key + '-' + dict[key])
Output:
This is a Python dictionary for the key values pair:
{'p': 'PYTHON', 'm': 'Mac', 'c': 'C++'}
Iterating a Python dictionary and retrieving the values in it:
p-PYTHON
m-Mac
c-C++
Python Iterators
Technically, two methods are attached to a Python iterator class object when it is created. The iterator protocol is the aggregate name for these two iterator class methods.
Method 1: __iter__()
The __iter__() method is automatically called when attempting to generate an iterator object in Python by submitting an Iterable object to the iter() function. From the Iterable object, it is utilised to initialise an iterator object. It is possible to iterate across Iterable objects like lists, tuples, dictionaries, etc. using the iterator object that this method provides.
Method 2: __next__ ()
The __next__() method is automatically used when iterating through Iterable objects in Python. It is used to loop through all of the iterator object's parts. When combined with its iterator, it returns the subsequent element or value of the Iterable object. When there is no item or element left in the Iterable object that can be returned by that method, the __next__() function plays a critical role in halting the iteration of the Iterable objects by raising the StopIteration Exception. How are Iterable transformed into iterators?
In Python, we can quickly turn an Iterable object—such as a list, a set, a tuple, etc.—into an iterator object by passing the Iterable object to the iter() function, which then calls the __iter__() method on the Iterable object.
Let's build an iterator object in Python from an Iterable object and see how the iterator class's __iter__() and __next__() methods function.
Program:
# Create an Iterable object for understanding the Iterable
# here it's a Python list where the values are assaigned to the list.
it_value = ['c', 'c++', 'python']
#printing the type of the values assaigned to it.
print(type(it_value))
#printing the values assaigned to the list.
print(it_value)
# Create an iterator object for iterating the list.
# from the above Iterable object (Python list) with the help of using the above list we are assaigning the Iterable .
# using the __iter__() method for iterating.
iterator_obj = it_value.__iter__()
print(type(iterator_obj))
# Iterate through the Iterable object.
# using its iterator object & the __next__() method we are performig the iteration.
print(iterator_obj.__next__())
print(iterator_obj.__next__())
print(iterator_obj.__next__())
# Raise the StopIteration Exception of the values.
print(iterator_obj.__next__())
Output:
<class 'list'>
['c', 'c++', 'python']
<class 'list_iterator'>
c
c++
python
Traceback (most recent call last):
File "<string>", line 20, in <module>
StopIteration
The Iterable object (a Python list) was created in the Python code above, converted to an iterator object using the __iter__() method, and its elements were accessed using the __next__() method. We then looked at how the __next__() method raises the StopIteration Exception when called to access the Iterable object's next element when there are no more elements in the Iterable object.
Iterating through the Iterable object with the for loop
The for loop is frequently used in Python to iterate through the elements of an Iterable object, as demonstrated by the examples of Iterable objects above. Let's see how this for loop for iterators functions using Python code.
Code:
# Create an Iterable object here it's a Python tuple for assaigning the tuple values and performing the iteration.
Iterable = ('c', 'c++', 'python')
#printing the type of the assaigned values.
print(type(Iterable ))
# Printing the values assaigned to a tuple.
print(" The values within the tuple are : ",Iterable )
# Iterate through the Iterable object using a for loop and retrieving the values in it.
print("Iteration using for loop and printing the values.")
for i in Iterable :
print(i)
# Analyze the implemention of for loop to iterate through the elements of like how the elements are retrieved from the tuple by using the for loop.
# the Iterable object (Python tuple) using an infinite while loop and iterator protocol for retriving the values.
def for_loop(Iterable ):
# Create an iterator object from the passed Iterable object for retrieving the values from the assaigned tuple.
# using the iter() function for retrieving the values assaigned to the tuple using the for loop.
iterator = iter(Iterable )
# Run an infinite while loop so we are using try execution that is exceptional handling techinques that means if the exception occurs also then it will give the values.
while True:
try:
# Access the each element of the Iterable object from the tuple.
# using the next() function for accesing the values from the given tuple.
print(next(iterator))
except StopIteration:
# If the StopIteration Exception is raised then it we have to break the block.
# by the next() function break the while loop and quit from the loop.
break
# Driver Code to check the implementation of the for_loop() function for knowing how the iteration is working inside the tuple values.
print("Iteration using for_loop function for knowing how the iteration is working inside the tuple values :")
for_loop(Iterable )
Output:
<class 'tuple'>
The values within the tuple are : ('c', 'c++', 'python')
Iteration using for loop and printing the values.
c
c++
python
Iteration using for_loop function for knowing how the iteration is working inside the tuple values :
c
c++
python
The Python code above demonstrates how a while loop that never ends is really utilised to create a for loop that iterates over the components of an Iterable object. When we use a for loop to iterate through an Iterable object, we first build an iterator object by executing the iter() function, after which we execute an endless while loop and access the subsequent element of the Iterable object using the next() function. The iteration ends when the next() function throws the StopIteration Exception because there are no more elements in the Iterable object.
Conclusion
- We have learned the following topics through this tutorial.
- Python distinguishes between iterator and Iterable objects using the __iter__() and __next__() methods of the iterator class.
- An Iterable object is transformed into an iterator object.
- Using a for loop, iterate through the Iterable object's elements.