Python Iterators Tutorial

Python Iterator; Through this tutorial, i am going to show you what is python iterators and how to use built-in iterators with lists, tuples and implement your own using classes.

Python lists, tuples, dictionaries, and sets are with python built-in iterators. Again, Iterators are the objects that can be iterated upon.

Python Iterators

In python, you can build easily your own iterator using __iter__ and __next__ methods. In Python, an iterator is an object which implements the iterator protocol, which consists of __iter__ and __next__ methods.

Iterators are used everywhere in Python, like with List, Tuple, Dictionary, Set, etc. They are elegantly implemented within the for loops, comprehensions, generators, etc. but hidden in plain sight.

What is use of iterator in python?

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.

How do you write iterator in python?

There are 4 ways to build an iterative function:

  1. create a generator (uses the yield keyword)
  2. use a generator expression (genexp)
  3. create an iterator (defines __iter__ and __next__ (or next in Python 2. x))
  4. create a class that Python can iterate over on its own (defines __getitem__ )

How to create an Iterator in Python

If you want to create an object/class as an iterator, you have to implement the methods __iter()__ and __next()__ to your object. 

Let’s see the following example:

class App:
    def __iter__(self):
        self.number = 1
        return self
    def __next__(self):
        data = self.number
        self.number += 1
        return data
IClass = App()
myiter = iter(IClass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

In the above example, have defined one class App. and after that, defined two methods __iter()__ and __next()__. The __iter()__ function returns the number and then __next()__ function increments the number by 1.

See the following output of above python program:

1
2
3
4
5
6

Iterating Through an Iterator in Python

Use the next() method to manually iterate through all the elements of an iterator. When you reach the end and there is no more data to be returned, it will raise StopIteration.

See the following example.

my_list = [21, 19, 29, 46]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)

The following is an example output:

 21
 19
 29
 46

Difference between Iterator and Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers that you can get an iterator from. 

All these objects have an iter() method which is used to get an iterator. Let’s take the example of an iterator.

listK = ['DF', 'FA', 'FSE']
itreables = iter(listK)
print(next(itreables))
print(next(itreables))
print(next(itreables))

See the output.

 DF
 FA
 FSE

In the above python program, defined a single list and then pass the list to the python iter() function. Which returns the iterator on which can call the next() method, and it will return the one item one by one.

The __iter__ method is called on the initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.

Next, talk about __next__   methods:

The __next__  method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object.

Let’s take a string as an example because strings are also iterables.

stringK = 'PYTHON'
itreables = iter(stringK)
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))

See the following output of the above python program:

 P
 Y
 T
 H
 O
 N

Also take a example of iterator with python tuple, you can see the python program below:

tupleK = ('list', 'map', 'filter')
itreables = iter(tupleK)
print(next(itreables))
print(next(itreables))
print(next(itreables))

The output of the following above python program:

 list  map  filter

Recommended Python Tutorials

Recommended:-Python Data Types
Recommended:-Functions in Python
Recommended:-Python Modules
Recommended:-Python Lists
Recommended:-Python Strings

Be First to Comment

Leave a Reply

Your email address will not be published.