DEV Community

iffishells
iffishells

Posted on

Python Generator's and How to used them

Agenda :

  • What are Generators?
  • Normal function vs Generator
  • Advantages of using Generator
  • Generator with loops
  • Generator with function
  • Generator Expression
  • Use Cases

what are Generator in Python?

Generators are basically function that return the traversable object or items. Generator do not produce the output at once time but Generator produce the output when we need them. Generator has lots of advantages some of them we will discuss Here :)

Advantages of using Generator

  • without the Generator in python producing the iterables is becomes very difficult and lenghty.
  • Generator easy to implement as they automatically implement is __iter()__ and __next()__ and stopiteration
  • They can also used pipeline a numbe of operations
  • can be used to produce an infinite number of items
  • Memory is saved as item is produced when we required unlike the in normal function. This facts becomes very important when you need to create a huge number of iterators.

Normal Function VS Generator Functions :

The difference between Normal and Generator function is only keyword return to yield. in the normal function return the output but in the Generator function yield return the object of list . using next() we get the number using the object . in the Normal function we call the function by his function name but in the generator function we called them by next().

Generator Function
#Genarator function
def func(a):
    yield a #change keyword return to yield
a = [1,2,3]
b=func(a)
next(b)

output --->
[1 , 2 , 3 ]
using next()
def myfunc(a):
    while a>=3:
        yield a
        a=a+1
b =  myfunc(a)
print(b)
next(b)
Normal function
def func(a):
    return a
a=[1,2,3]
func(a)

output -->
[1 ,2 , 3]

if you look the code above you will observer the return change into the yield but their functional completly opposite. yield return the object of the output using next() and we get it . Normal function called by his name but Generator function called by next(). you will realize after see the below image.

Generator with loops

In case you want to execute the same function at once, you can make use of the ‘for’ loop. This loop helps iterate over the objects and after all implementations it executes StopIteration.

def z():
    n=1
    yield n
    n=n+3
    yield n
for x in z():
    print(x)


output --->>
1 
4

Generator Expression :

You can also use the expression along with the loop for loop procedure iterators. this makes the generation iterables and easy to understand.

print("Generator Expression " , end= " :n ")
range_list=range(6)
ret =  (number for number in range_list)
print(c)
for ret_number in ret:
   print(ret_number)

Major Difference

As we said Generator makes the code pretty and readable and taking less memory and less code and as well as reduce the code . now its time to look first i will write the code without the generator and then with generators then you will see the difference and blessing of the generator in python.

Code without using Generator
class Nums:
    MAX = 4
    def __init__(self):
        self.current = 0
    def __iter__(self):
        return self
    def __next__(self):
        next_value = self.current
        if next_value >= self.MAX:
            raise StopIteration
        self.current += 1
        return next_value
Code with Generator
def func(var1):
    yield var1
    var1 +=1

Top comments (0)