Advance Python - Generators


NaN years ago

The biggest weakness of normal functions in python is large memory consumption while running big functions and variable destruction after the end of a function. If you want to reuse the calculated variables then the normal function needs to execution again to avoid this problem python provides special functions called generators.

Generators are similar to normal functions except for output syntax and execution methods. A normal function starts execution from line one and continues till the function returns, breaks or throws an exception then destroy all local variable whereas generators continue till the next yield and store the local variables then give the output.

// Example 1
def generator_thr_iter():
   yield 'xyz'
   yield 246
   yield 40.50
>>> g = generator_thr_iter()
>>> g.__next__()
>>> g.__next__()
>>> g.__next__()

// Example 2
def num_generator(n):
num =1
while True:
   yield num
   if num == n:
      num += 1
for i in num_generator(200000000000):
   print (i*i)

// this function doesn't take infinite to give output, it outputs value fast and take less memory but take time to return.

Pros of Generators in Python

  • Generators take less memory since they store one value at a time
  • Generators are used to control the iteration behaviour of the loop.
  • Generators' logic can be changed with parameters on each function call.

Cons of Generators in Python

  • You can not use generators to process code in bulk
  • Generators are not good enough for small functions.

Generators in Python are a very useful function in building large programs. To learn more about Generators and implement them in Python, please use free resources.

approvedApproved by experts
Advance Topics

Neuton's Mission

We are a team of young and enthusiastic people who are passionate about education and want to help students to learn the skills they need to succeed in life. If you want to support us, please join our community.