Mastering Python (64 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (28 Blogs)
  • Data Science (39 Blogs)
  • Mastering Python (59 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Python Iterators: What is Iterator in Python and how to use it?

Published on Sep 04,2019 62 Views
36 / 40 Blog from Python Fundamentals

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Hey, this blog will cover the most favorite topic of the programmers and coders i.e. Iterators in Python. We will be doing an in-depth study on the iterators and how they work in Python programming language. Stay with us till the end.

So, here we are going to cover the following topics in order to have a clear understanding of the topic:

Let’s begin.

What is iterator in Python?

A python iterator is a container containing a countable number of values. Values in a container can be traversed using Iterators (Particularly lists).

Apart from traversal, Iterators also gives access to data elements in a container but does not itself perform iteration (i.e., not without some significant liberty taken with that concept or with trivial use of the terminology. An iterator is almost similar to a database cursor in behavior

Iterator in Python

Iterator is any type of Python that can be used with a ‘for in loop’. 

 Any object that is to be used as an iterator must implement the following methods.

1. __iter__ method. 

It is called on initialization of an iterator. 

It should return an object that has a next or __next__  method.

2.  next. The iterator next method returns the next value for the iterable. 

When an iterator is used with a ‘for in’ loop, next() is implicitly called by for loop on the iterator object. This method should use a StopIteration to signal the end of the iteration.

Together these two methods are called Iterator Protocol.

Below is a simple Python program that creates iterator type to iterate from 10 to given limit. For example, if limit is 17, then it prints 10 11 12 13 14 15 16 17. And if limit is 8, then it prints nothing.

Take a look at the below example demonstrating the working of iterators that iterates from 10 to given value.

 

# An iterable user defined type 
class Test: 

	# Cosntructor 
	def __init__(self, limit): 
		self.limit = limit 

	# Called when iteration is initialized 
	def __iter__(self): 
		self.x = 10
		return self

	# To move to next element. In Python 3, 
	# we should replace next with __next__ 
	def next(self): 

		# Store current value ofx 
		x = self.x 

		# Stop iteration if limit is reached 
		if x > self.limit: 
			raise StopIteration 

		# Else increment and return old value 
		self.x = x + 1; 
		return x 

# Prints numbers from 10 to 15 
for i in Test(15): 
	print(i) 

# Prints nothing 
for i in Test(5): 
	print(i)

How to implement iterators in Python

Iter() method

All these objects, lists, tuples, dictionaries have an iter() method which can be used to get an iterator:

Example:

Run an iterator from a tuple and print each value:

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

OUTPUT

C:UsersMy Name>python demo_iterator.py
apple
banana
cherry

Strings are also iterable objects, and can return an iterator:

Example:

Strings are iterable objects which contain a sequence of characters

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

OUTPUT

C:UsersMy Name>python demo_iterator2.py
b
a
n
a
n
a

 

For loop to iterate through an iterable object

Using the ‘for’ loop is a more elegant way of automatically Iterating values.

Example:

mytuple = ("apple", "banana", "cherry")
for x in mytuple:
  print(x)

OUTPUT:

C:UsersMy Name>python demo_iterator_loop.py
apple
banana
cherry

Now, Let’s see how to iterate characters of a String using FOR loop

mystr = "banana"

for x in mystr:
  print(x)

OUTPUT:

C:UsersMy Name>python demo_iterator_loop2.py
b
a
n
a
n
a

StopIteration

In this section, we will be knowing about an important feature of Iterators i.e. StopIteration

To understand what it means we will first go through a code.

Here we create an iterator that returns numbers, starting from 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.)

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

The example above would continue forever if we had unlimited next() statements, or if it was used with a for loop.

To prevent this iteration to go on forever, we use the StopIteration statement. In the __next__() method, we add a terminating condition to raise an error if the iteration is done a specified number of times (which is 20 in the below example)

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)


As soon as the Iterator reaches 20, it will terminate the Iteration and prevent it from going on forever.

Python Infinite Iterators

It is not always mandatory that the item in an iterator object has to exhaust. There can be infinite iterators (which never ends). Here is a basic example to demonstrate infinite iterators.

The built-in function iter() can be called with two arguments where the first argument must be an object (function) that can be called and second is the sentinel. The iterator calls this function until the returned value becomes equal to the sentinel.

>> int()
0

>> inf = iter(int,1)

>> next(inf)
0

>> next(inf)

0

We can see that the int() function always returns 0. So passing as iter(int,1), it will return an iterator that keeps calling int() until the returned value equals 1. This never happens and thus, we get an infinite iterator. We must be careful when handling such iterator.
This is all about Iterators in Python. Considering the usage of Iterators, it’s very important to learn about these and how to implement it in an effective way. Since you have reached this far, you might now be in a position to make Iterators of your own.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access.

Thanks for reading, I hope it helped. Keep Learning.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.