Generators in Python

Previous
Next

Generators:

  • Generators are solution to overhead of Iterators.
  • We have to implement a class with __iter__() and __next__() method, keep track of internal states, raise StopIteration when there was no values to be returned etc.

Create a generator:

  • It is fairly simple to create a generator in Python.
  • It is as easy as defining a normal function with yield statement instead of a return statement.
  • If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function.
  • Both yield and return will return some value from a function.
# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n
    return

obj = my_gen()
next(obj)
next(obj)
next(obj)
  • One interesting thing to note in the above example is that, the value of variable n is remembered between each call.
  • Unlike normal functions, the local variables are not destroyed when the function yields. Furthermore, the generator object can be iterated only once.
  • To restart the process we need to create another generator object using something like a = my_gen().

Note: One final thing to note is that we can use generators with for loops directly.

# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n

# Using for loop
for item in my_gen():
    print(item)    
Previous
Next

Add Comment

Courses Enquiry Form