Learn Python Programming

Python Generators


A generator is a special type of function in Python which does not return a single value, instead it returns a sequence of values. Generators is an easier way to create iterators using a keyword yield from a function rather than a return keyword.

  • Generators are defined with the def keyword.
  • It uses the yield keyword.
  • It can use several yield keyword.
  • It returns an iterator.

Let us understand with an example:

Example 1:

def my_generator(x,y):
    while(x<=y):
        yield x
        x+=1

print(my_generator)

#OUTPUT
<function my_generator at 0x00F40810>

So whenever you will use yield keyword in a function it will become a generator. But how will you iterate? As generator returns an iterator, so you can iterate through iterator like example 2 :

Example 2:

def my_generator(x,y):
    while(x<=y):
        yield x
        x+=1

mygen = my_generator(1,5)

for i in mygen:
    print(i)

#OUTPUT
1
2
3
4
5

Example 3:

def my_generator():
    name    = 'Deepak'
    age     = 30
    dob     = '18 October 1990'
    yield name
    yield age
    yield dob

my_iter = my_generator()
try:
    print(next(my_iter))
    print(next(my_iter))
    print(next(my_iter))
    print(next(my_iter))
except StopIteration as ex:
    print("Iterator Stop!")

#OUTPUT
Deepak
30
18 October 1990
Iterator Stop!