Python Iterator

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

Python Iterables vs Iterator

If we can get an iterator from it, then we call that object as Python 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 Iterator in Python and create our own iterators and infinity iterators with practical examples.

Python String Iterator 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 Iterator concept without your knowledge.

# Python Iterator Example
 
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 Iterators For loop Example 2

In this example, we used both for loop and iterators. In python, we have to use the next() function to return an element or value from an iterator. Remember, the Python next() function 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**** Iterator Example *****")
itr = iter(string)
  
print(next(itr))

Iterator vs For Loop output

t u t o r i a l g a t e w a y
**** Iterator Example *****
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**** Iterator 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))
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 g a t e w a y
**** Iterator Example *****
t
u
t
o
r
i
a
l
g
a
t
e
w
a
y

Python List Iterator

In this 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))

List iterator output

10
20
30
40
50

In this list iterator 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 Python Iterator 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

You can use the Iterator to iterate the set items too. 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__())

set iterator output

1
2
3
4
5

Tuple Iterator

Python also allows you to use this 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))

Tuple iterator output

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 Iterator 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

Python Own Iterator Example 2

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

Python Infinity Iterator

While you create your own iterator, you should always be careful with Infinity loops. If you forget to raise the StopIterator 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))

Infinity Iterator output 1

0
1
2

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

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

Now you can see the Python infinity iterator. This iterator executes continuously. Please refer to Python Dictionary article.

267
268
269
270
271
272
273