Python Iterator

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

Python Iterator Vs Iterables

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

Python Iterator String Example

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

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

Python Iterator For loop Example 2

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

Remember, the Python 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.

string = 'tutorialgateway'
  
for x in string:
     print(x, end = '  ')
  
print("\n**** Output *****")
itr = iter(string)
  
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 iterate all the characters in a string. This time, the Python writes the completed string.

string = 'tutorialgateway'
 
for x in string:
    print(x, end = '  ')
 
print("\n**** Example *****")
itr = iter(string)
 
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 Iterator List example

In this iterator example, we show how to iterate 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 Iterator Set Example

You can use this to iterate the set items and returns the iterator object. This program iterates 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 Iterator

Python iterator 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. 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))
Python Iterator 8

The above Python iterator 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

Infinity Iterator

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. 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 Python 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. This executes continuously.

267
268
269
270
271
272
273