Generator

  • Python generators are a simple way of creating iterators
  • generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
  • If the body of a def contains yield, the function automatically becomes a generator function.

Why it is needed ?

  • For building an Iterator , we have to implement a class with __iter__() and __next__() method, keep track of internal states, and raise StopIterationwhen there are no values to be returned.
  • To avoid lengthy and counterintuitive , we use Generators

Create Generators 

  • It is similar like defining a normal function, but with a yield statement instead of a return statement.
  • The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.
def GeneratorFun():

    yield 1            

    yield 2            

    yield 3            

for var in GeneratorFun(): 

    print(var)
# Initialize the list

my_list = [1, 3, 6, 10]

a = (x**2 for x in my_list)

print(next(a))

print(next(a))

print(next(a))

print(next(a))

next(a)

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *