Python Iterators

In this tutorial you will learn:

  • Iterators
  • Iterators in Python
  • Developing your own Iterator


We use iterator when we want to go through all elements of collection. It doesn’t need a specific collection or data type, it works irrespective of implementation.

Iterators in Python

Iterator is an object in Python it implements the iterator protocol. A protocol is something that defines some methods and any class implementing that protocol must implement those methods. In Python the iterator protocol requires two fuctions to be implemented one is the __iter__ function and the other function is the next() function. Iterator object will be returned by the iter function and the next element must be returned by the next function.


  1. st = "Python"
  2. val = iter(st)
  3. print('First letter is: ',next(val))
  4. print('Second letter is:',next(val))
  5. print('Third letter is: ',next(val))
  6. print('Fourth letter is:',next(val))
  7. print('Fifth letter is: ',next(val))
  8. print('Sixth letter is: ',next(val), '\n')

Here we can see that the after passing the value to iter we can simply print the values using the next function. Let's look at another example.

  1. list = ["Python","Testing", 5]
  2. val = iter(list)
  3. print(next(val))
  4. print(val.__next__())
  5. print(val.__next__(), '\n')

In this example we are using next function with the iterator name which is similar to calling next function and then passing the iterator.

Developing your own Iterator

In order to develop your own iterator you need to implement the iterator protocol and it requires __iter__ and __next__ methods. Iter function is used to initialize the values and returns iterator object. Next function returns the very next value that comes in a list or sequence.

Example In this example we will create an iterator which will return the number with the power of two on every next iteration.
  1. class Power:
  2. def __iter__(self):
  3. self.num = 0
  4. return self
Here we created a power class and added the required __iter__ function. But we need to write another function which is the next function.
  1. def __next__(self):
  2. result = 2 ** self.num
  3. self.num+=1
  4. return result
Now let's use our newly developed iterator to get the value of two raised to the power number starting from 0.
  1. power = Power()
  2. it = iter(power)
  3. print('2 raised to the power 0 :',next(it))
  4. print('2 raised to the power 1 :',next(it))
  5. print('2 raised to the power 2 :',next(it))
  6. print('2 raised to the power 3 :',next(it))

Add new comment