Python Programming

Tutorial No. 6 : Generators and Iterators

Iterators in Python

Iterators are objects that can be iterated upon. An object which will return data, one element at a time.Python iterator objects should implement two methods, __iter__() and __next__(), collectively called the iterator protocol.An object is called iterable if we can get an iterator from it. For example: list, tuple, string etc. are the iterables.

# define a list
l = ['A','B','C','D']

# get an iterator using iter()
my_iter = iter(l)

# iterate through it using next()

# Output: A
print(next(my_iter))

# Output: B
print(next(my_iter))

# Usage of __next__() method
# Output: C 
print(my_iter.__next__()) 

# Output: D
print(my_iter.__next__())

# This will raise error, no data is left
next(my_iter)
                                

Generators in Python

Generators are also one type of user defined functions which generates some value.yield() method is used to generate the values.

                                # A simple generator function
def simp_gen():
    n = 1
    print('This will print '+str(n))
    # Generator function contains yield statements
    yield n
    
    n = n+1
    print('This will print '+str(n))
    yield n

    n = n+1
    print('This will print '+str(n))
    yield n

a = simp_gen()
# This will print 1
next(a)
# This will print 2
next(a)
# This will print 3
next(a)
# This will print an Error
next(a)
                                

Exercise

Definition : 1 Display the sum of first n numbers using generator and Iterator. Value n will be entered by the user.
Solution using Iterator

#Take Input from user
n = int(input('Enter Value of N '))

#Create a list
l = range(1,n+1)

sum = 0
#Make List iterable
l_iter = iter(l)

i=0

#Calculate Sum
while i < n:
  sum = sum + next(l_iter)
  i = i+1

print('Sum is ' +str(sum))
                                
Solution using Generator