Python Iterators

[vc_row][vc_column][vc_column_text]An Iterators are objects that allow you to transverse through all the values. They are iterate through for loop. 

Python Iterator object must implement  iterator protocol which consists of two methods __iter__() and  __next__().

Python List, Tuple, String and Dictionary are the built-in iterable object in Python. All these objects used iter() method to get an iterator from. We can also use a for loop to iterate through an iterable object.

# Iterate the list value using for loop
fruit_list = ['banana','apple','Orange']
for e in fruit_list:
    print(e)

The for loop actually create the iterator object and execute the next() method for each iteration.

Execute an iterator from the list, and print each values using iter() method.

fruit_list = ['banana','apple','Orange']
fruit_iter = iter(fruit_list)
print(next(fruit_iter))
print(next(fruit_iter))
# Output
banana
apple

.     .     .

Create an Iterator

To create your own iterator is easy in Python. We just need to implement two methods __iter__() and __next__() to your object.

  • __iter__() : a method that performs initialization operation and returns an iterator object itself.
  • __next__() : a method that performs operations and returns the next item in the sequence.

 

Example:

Create an iterator that returns odd numbers, starting with 1.

class oddNumber:
    def __iter__(self):
        self.a = 1
        return self
    
    def __next__(self):
        x = self.a
        self.a += 2
        return x

Object_odd = oddNumber()
odd_iter = iter(Object_odd)

print(next(odd_iter))
print(next(odd_iter))
print(next(odd_iter))
print(next(odd_iter))
print(next(odd_iter))
# Output
1
3
5
7
9

.     .     .

StopIteration

StopIteration statement used to prevent the iteration to go on forever. In the __next__() method, we can add a stop condition to raise an error if the iteration is iterated a specified number of times.

Example:

Create an iterator that returns odd numbers between 1 and 20.

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

Object_odd = oddNumber()
odd_iter = iter(Object_odd)
for e in odd_iter:
    print(e)
# Output
1 3 5 7 9 11 13 15 17 19

.     .     .

[/vc_column_text][/vc_column][/vc_row]

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials