Introduction to Iterator in Python
An iterator in python is a method that loops the program through the iterator protocol. This concept consists of two key elements, the iterator and the iterable. The object on which the iterator iterates are called iterable.
The iterator protocol is built by means of below three segments.
- The constructor is achieved using the init function, and the maximum value for the iteration is assigned here.
- The special __iter__ function is used for assigning the initial value.
- The special __next__ function is used for looping through each value of the iterator.
Examples of Python Iterator
Given below are different examples of Iterator in Python:
Example #1
Sample iterator protocol.
Code:
class sample:
# Constructor
def __init__(self, limit_value):
self.limit_value = limit_value
# Called when iteration is initialized
def __iter__(self):
self.iterator = 0
return self
# To move to next element.
def __next__(self):
# Store current value ofx
x = self.iterator
# Stop iteration if limit is reached
if x > self.limit_value:
raise StopIteration
# Else increment and return old value
self.iterator = iterator + 1;
return iterator
Example #2
Manually driven iterator program.
In the below program, the process of the iterator is manually driven in the program itself by statically calling the iterator initialization and iterator sequencing methods.
Code:
class sample:
# Constructor
def __init__(self, lastelement):
self.lastelement = lastelement
def __limit__(self):
return self.lastelement
# initialization of iteration
def __iter__(self):
self.iterator_value = 1
return self.iterator_value
# move to next value or element.
def __next__(self):
# ofx current value stopped
iterator_value = self.iterator_value
# iteration stopped on limit reached
if iterator_value > self.lastelement:
raise StopIteration
# Else increment and return old value
self.iterator_value = iterator_value + 1;
return iterator_value
# declaration of object
# processed count
var1=int(input( " Enter the limit : " ) )
Object = sample(var1)
iterator = Object.__iter__()
loopcount = Object.__limit__()
while(iterator < loopcount):
print("The value of iterator now is : ",iterator)
iterator = Object.__next__()
Example #3
In-built iterators.
The below program implies the use of iterator over inbuilt python entities like list, tuple, string, dictionary.
Code:
# A list value is been iterated
print("Iteration over a list")
l = [ " One " , " Two " , " Three " , " Four " , " Five " ]
for iterator_element in l:
print(iterator_element)
# A tuple value is being iterated
print("\n Iteration on a tuple ")
t = ( " One " , " Two " , " Three " , " Four " , " Five " )
for iterator_element in t:
print(iterator_element)
# A string value is been iterated
print("\n Iteration on a String")
s = "Test"
for iterator_element in s :
print(iterator_element)
# A dictionary value is been iterated
print("\n Iteration on a dictionary element")
d = dict()
d[ '1234567890' ] = 1
d[ 'abcdefghij' ] = 2
for iterator_element in d :
print("%s %d" %(iterator_element, d[iterator_element]))
Explanation:
- The program iterates across four different iterable objects such as list, tuple, string and dictionary with the iterator “i”.
Output:
Example #4
Loop control statement.
This program iterates through a set of given car types and prints the corresponding cars in the market under each of the mentioned types. This process is achieved by two looping instances a while, and a for loop is nested into the while. The key element to note is that the for loop is performed over a list by means of a specific iterator value.
Python program using loop control statements:
Code:
var_a = 1
var_b = 2
while var_a < var_b:
var_c = [ " SUV " , " sedan " , " hatchback " , " End " ]
for iterator in var_c:
if iterator == " SUV ":
print( " Jeep " )
print( " Kia Seltos " )
print( " Suzuki Ertiga " )
print( " Huyndai venue " )
print( " Scorpio " )
print( " Hyundai Creta " )
print( " ----- END OF SUV CARS -------- " )
if iterator == " sedan " :
pass
if iterator == " hatchback " :
print( " Hyundai i20 " )
print( " suzuki alto " )
print( " Renault KWID" )
print( " Wagon R " )
print( " Tata Tiago " )
print( " Maruti Ceerio " )
print( " Hyundai Santro " )
print( " Tata Nano " )
print( " --------------- " )
if iterator == "End":
break
var_a = var_a+1
Output:
Example #5
For loop.
This program uses iterator oriented for loop technique for designing a dictionary collection data type. This collection datatype is formulated by piling two independent list elements.

4.8 (13,748 ratings)
View Course
Code:
# Program for list to dictionary concatenation #
#Variable declaration
Key_elements=[]
value_elements=[]
# Total nuumber of elements to be processed
var1=int(input( " Count of elements for the dictionry : " ) )
print("--------------------KEY_ELEMENTS-----------------------")
for x in range(0,var1):
element= int ( input ( " Element value entered " + str(x+1) + " : " ) )
Key_elements.append(element)
print("--------------------VALUE_ELEMENTSS---------------------")
for x in range(0,var1):
element= int ( input (" Element value entered" + str(x+1) + ":"))
value_elements.append(element)
d= dict ( zip ( Key_elements , value_elements ) )
#Print Section
print("The dictionary formulated is:")
print(d)
Output:
Benefits of Python Loops
Given below are the benefits mentioned:
- Code reduction.
- Code redundancy is greatly resolved.
- Reduces code complexity.
- It brings more stability into coding.
Conclusion – Iterator in Python
The dominance shown signs of by any programming language depends on the classified set of coding functionalities. In such instance, python programming’s iteration resource is principally steady and supple to code, making it out to be among the prior reasons that make this language dominate the market. Concepts of like iterators make python among the most sophisticated language of program development, and additionally, the language holds out to be with such significance in the software development environment.
Recommended Articles
This is a guide to the Iterator in Python. Here we discuss the introduction, examples and benefits for better understanding. You may also have a look at the following articles to learn more–