Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Generators in python

In this chapter, you will learn about the generators in python. In the last chapter, we studied about the decorators in the python, now its time to look into the generators in the python. If you are familiar with javascript, it would be easy to learn the generators.

Generators:

  1. Generators functions are like the normal functions, there is the only a difference in syntax
  2. Generator functions allow us to create a function that can send back value and then later resume to pick up where it left off.
  3. In simple words, generators functions help in creating the sequence of values over a time
  4. The difference between the decorators’ function and normal function is the use of yield statement
  5. When a generator function is compiled they become an object that supports an iteration protocol
  6. Which means when they are called in your code they don’t actually return a value and then exit
  7. Generator functions have the capability to automatically suspend and resume the execution and state around the last point of value generation
  8. The benefit of generators is that it computes the one value and waits until the next value is called for

Let’s write an example for generating the Fibonacci series using the generators

def fibonacci_generator(n):
    print('Generator function to print the fibonacci series')
    a=1
    b=1
    for i in range(n):
        yield a
        a,b = b, a+b

for number in fibonacci_generator(10):
    print(number)

# output
# Generator function to print the fibonacci series
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34
# 55

Now there is next() function is available with the generator function, let’s see how can we use the next() function with the same example

def generator_with_next():
    for n in range(5):
        yield n

print('Print using the generator and for loop function')
for number in generator_with_next():
    print(number)

# Using the next function
copyg = generator_with_next()

print('\n Print using the next function')
print(next(copyg))
print(next(copyg))
print(next(copyg))
print(next(copyg))
print(next(copyg))
print(next(copyg))

# output
# Print using the generator and for loop function
# 0
# 1
# 2
# 3
# 4

#  Print using the next function
# 0
# 1
# 2
# 3
# 4
# Traceback (most recent call last):
#   File "gene.py", line 42, in <module>
#     print(next(copyg))
# StopIteration

Generators in python example with next

Generators in python with code snippet

One thought on “Generators in python

Comments are closed.