python,

Iterator in Python

Tony Tony Follow Nov 15, 2019 · 1 min read
Iterator in Python
Share this

Definition

Iterator is any type of python object that can be used in ‘for loop’. An iterator must implement the following methods:

  • _iter_
  • next (_next_ in python3)

Python lists, tuples, dicts and sets are all inbuilt iterators.

Example

Below is a example of python program that create a fibonacci iterator that iterate from 1 to given limit. For example, if limit is 5, then it would print 1, 1, 2, 3, 5. And if limit is less or equal than zero, then it would print nothing.

_iter_

This method is called on initialization of an iterator. It should return a object which has a next or _next_ method.

next ( _next_):

The iterator should have a next (_next_) method to return the next value for a iterate. The for loop would implicitly call the next (_next_) method during the iteration. This method should raise a StopIteration to signal the end of iteration.

class IteratorDemo:
    def __init__(self,limit):
        self.limit=limit
    
    def __iter__(self):
        self.x=0
        self.y=1
        return self
    
    def __next__(self):
        if self.y>self.limit:
            raise StopIteration
        self.x,self.y=self.y,self.x+self.y
        return self.x


for i in IteratorDemo(5):
    print(i)

Output:

1
1
2
3
5
for i in IteratorDemo(-1):
    print(i)
# Output nothing
Join Newsletter
Get the latest news right in your inbox. We never spam!
Tony
Written by Tony Follow
Hi, I am Tony, the author of Learning Journey blog. I hope you like what I sharing!