Python Iterator

An Iterator in Python is an Object which contains a countable number of values or elements. You can use this one to Traverse all those elements. The Python iterator uses the special methods called __iter__() and __next__() methods to traverse the object elements.

Python Iterator Vs Iterables

If we can get the Python iterators from it, then we call that object as iterable. So far, we have seen the objects called Lists, Tuples, Sets, and Dictionaries. From these objects, you can call Iter. This section explains how to use this Python class and create our own and infinity iterators with practical examples.

String Iterator Example

In python, strings are iterable objects. Here, we use for loop to loop each character in a string and returns that character. By default, or say, For loop implements the Python Iterator object concept without your knowledge.

stri = 'tutorialgateway'
 
for x in stri:
    print(x, end = '  ')
t u t o r i a l g a t e w a y

Python For loop Iterator Example 2

In this example, we used both for loop and this. In python programming languages, we have to use the next() function to return an element or value from an iterator.

Remember, the next() method returns one item at a time. So, for n number of items, you have to use n next() statements. Here, we used the next() for one time. So, it returns the first character from a string.

stng = 'tutorialgateway'
  
for x in stng:
     print(x, end = '  ')
  
print("\n**** Output *****")
itr = iter(stng)
  
print(next(itr))
t u t o r i a l g a t e w a y
**** Output *****
t

Let me use next() to traverse all the characters in a string. This time, iterators writes the completed string.

sting = 'tutorialgateway'
 
for x in sting:
    print(x, end = '  ')
 
print("\n**** Example *****")
itr = iter(sting)
 
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
t u t o r i a l
**** Example *****
t
u
t
o
r
i
a
l

Python List Iterator example

In this example, we show how to traverse List items and prints them.

numbers = [10, 20, 30, 40, 50]
 
itr = iter(numbers)
 
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
10
20
30
40
50

In this list example, we used the __next__() special method. If you observe the last statement, we are trying to return the next element that doesn’t exist. That’s why Iter is calling StopIteration.

numbers = [10, 20, 30, 40, 50]
 
itr = iter(numbers)
 
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
Python Iterator 5

Python Set Iterator Example

You can use this to traverse the set items and returns the object. This program traverse the numbers in a Set and prints each one of them.

mySet = {1, 2, 3, 4, 5}
 
ittr = iter(mySet)
 
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
1
2
3
4
5

Tuple Example

The Python iterator object can also allows you to use on Tuples as well. This program iterates Tuple items and prints each item in a tuple.

fruits = ('Apple', 'Orange', 'Grape', 'Banana', 'Kiwi')
 
fruit_itr = iter(fruits)
 
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
Apple
Orange
Grape
Banana
Kiwi

Create Own Iterator in Python

It is a simple class called Counter. In this example, first, we declared a maximum value within the __init__ method. The __iter__ method is to initialize the value of an iterable object. For now, we set the number to 0. It means Iter starts at 0.

The __next__ method is to select the next element from an Object. Within this method, we used the If Else Statement to check whether the next number is greater than the maximum value or not. If True, StopIteration error raised. Otherwise, the number incremented.

class Counter:
 
    def __init__(self, maximum):
        self.maximum = maximum

    def __iter__(self):
        self.number = 0
        return self
 
    def __next__(self):
        number = self.number
 
        if number > self.maximum:
            raise StopIteration
        else:
            self.number = number + 1
            return number
 
numbers = Counter(10)
a = iter(numbers)

print(next(a))
print(next(a))
print(next(a))
Create Own Iterator in Python

The above iterator in python code is displaying numbers from 0 to 2. It is because we used next(a) for three times only. In this program, we used for loop to iterate the Counter class where the maximum value is 10. This prints the values from 0 to 10. __iter__() starts at 0, and __next__() print elements up to 10.

class Counter:
 
    def __init__(self, maximum):
        self.maximum = maximum
 
    def __iter__(self):
        self.number = 0
        return self
 
    def __next__(self):
        number = self.number
 
        if number > self.maximum:
            raise StopIteration
        else:
            self.number = number + 1
            return number
 
for t in Counter(10):
    print(t)
0
1
2
3
4
5
6
7
8
9
10

Python Infinity Iterator class

While you create your own iter, you should always be careful with Infinity loops. If you forget to raise the error, then you end up in infinity loops. It is a simple example of an infinity iterator object. It is the same as above, but we removed the If statement.

class Counter:
 
    def __iter__(self):
        self.number = 0
        return self

    def __next__(self):
        number = self.number

        self.number = number + 1
        return number
      
numbers = Counter()
a = iter(numbers)
 
print(next(a))
print(next(a))
print(next(a))
0
1
2

Although the above example is an infinite iter, you might not have noticed it. It is because we used the next() for three times only. So, let me use for loop to Ian iter function the Counter class. Please refer to Dictionary article.

class Counter:
 
    def __iter__(self):
        self.num = 0
        return self
 
    def __next__(self):
        num = self.num
 
        self.num = num + 1
        return num
     
for t in Counter():
    print(t)

Now you can see the Python infinity iterator object. This executes continuously.

267
268
269
270
271
272
273