Python iterators

Python Methods and Functions

Iterator in python — this is any type of python that can be used with a for in loop. Python Lists, Tuples, Commands, and Sets — these are all examples of built-in iterators. These types are iterators because they implement the following methods. In fact, any object that wants to be an iterator must implement the following methods.

  1. __iter__ the method that is called when the iterator is initialized. This should return an object that has a next or __next__ method (in Python 3).
  2. next (__next__ in Python 3) The next iterator 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. This method should call StopIteration to signal the end of the iteration.

Below is a simple Python program that creates an iterator type that iterates from 10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it doesn't print anything.

# Simple program in Python for demonstration
# work of iterators using an example like
# iterates from 10 to a given value

 
# Iterable custom type

class Test:

 

# Cosntructor

def __ init __ ( self , limit):

  self . limit = limit

 

  Called when the iteration is initialized

def __ iter __ ( self ):

self . x = 10

return self

 

# Move to next item. In Python 3

# we have to replace the following with __next__

def next ( self ):

 

# Save current x value

x = self . x

 

# Stop iteration if limit is reached

if x & gt;  self . limit:

raise StopIteration

 

# Otherwise, increment and return the old value

self . x = x + 1

return x

 
# Prints numbers 10 to 15

for i in Test ( 15 ):

print (i)

 
# Doesn't print anything

for i in Test ( 5 ) :

print (i)

Output:

 10 11 12 13 14 15 

Examples of built-in iterator types.

# Inline iterators example

 
# Loop through the list

print ( " List Iteration " )

l = [ " geeks " , " for " , "geeks" ]

for i in l:

print ( i)

 
# Loop over a tuple (immutable)

print ( "Tuple Iteration" )

t = ( " geeks " , " for " , "geeks" )

for i in t:

print (i)

 
# Iterate over a line

print ( "St ring Iteration "

s = "Geeks"

for i in s:

print (i)

 
# Looping through the dictionary

print ( "Dictionary Iteration"

d = dict () 

d [ ' xyz' ] = 123

d [ 'abc ' ] = 345

for i in d:

print ( "% s % d" % (i, d [i]))

Output:

 List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G eeks Dictionary Iteration xyz 123 abc 345