Iterators are objects that can be used to iterate all the items in iterable objects such as Lists, Tuples, Dictionaries, and Sets. It means iterators have the capability to traverse through the iterable objects. A few Examples of iterators are enumerate, map, filter, zip, and reversed. Iterators are basically implemented for loops, comprehensions, and generators.
Let’s create an iterator and print the next item as shown in the above diagram:
# Create a list
sample = [1, 2, 3, 4, 5]
# Create an iterator
sample_iter = iter(sample)
# Print the next item
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
print(next(sample_iter))
Output: 1 2 3 4 5
In Python, iterators can be created using an iterator object. In order to implement an iterator should have two methods __iter__() and __next__().
in order to avoid the iteration going on forever, raise the StopIteration Exception.
# Define class
class sample_iterator:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i < self.n:
i = self.i
self.i += 1
return self.i
else:
raise StopIteration
# Create Object
iter_obj = sample_iterator(9)
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
Output: 1 2 3 4
Let’s convert the iterator object into a list iterable:
iter_obj = sample_iterator(9)
print(list(iter_obj))
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Let’s use the iterator object in For loop:
iter_obj = sample_iterator(9)
for i in iter_obj:
print(i, end = " ")
iter_obj = sample_iterator(9)
while True:
try:
x = iter_obj.__next__()
print(x, end = " ")
except StopIteration:
break
Output: 1 2 3 4 5 6 7 8 9
In this tutorial, we will focus on MapReduce Algorithm, its working, example, Word Count Problem,…
Learn how to use Pyomo Packare to solve linear programming problems. In recent years, with…
In today's rapidly evolving technological landscape, machine learning has emerged as a transformative discipline, revolutionizing…
Analyze employee churn, Why employees are leaving the company, and How to predict, who will…
Airflow operators are core components of any workflow defined in airflow. The operator represents a…
Machine Learning Operations (MLOps) is a multi-disciplinary field that combines machine learning and software development…