generators and its usage in python


generators and its usage in python

Lets start with generators and its usage in python. A generator is a function in python which returns a python object. The returned object is aniterable object it like an array. Every object in the array is just a lazy function with parameters are ready for call. Generators are memory efficient because of its lazy evaluation. When we call method "__next__" on generator object it will evaluates object in the generator sequence and returns the value. Generators will not create an array containing all the values and returning them all at once. Instead generator yields the values one at a time, which requires less memory.

simple generator function with yield statement

def f():
    yield 1
    yield 2
generator = f()
# access an element in generators sequence
print(generator.__next__())
# Output: 1
print(generator.__next__())
# Output: 2
print(generator.__next__())
# Output: StopIteration: Error

In the above, the generator has two values. we can accessed the value from a generator with method "__next__". It has only two values when we try to access the third value, it raises an error called "StopIteration". It means generator has no object left that can generate the value.

Normal python function to get first "n" even numbers

def even_numbers(n):
    even_list = []
    for i in range(1, n):
       even_list.append(i * 2)
    return even_list
# Excecution
num_list = even_numbers(3)
for num in num_list:
    print (num)
# Output: 
2
4
print(num_list)
# Output: [2,4]

When we call above function it will create first "n" even numbers and stores it in the list and returns it. For this, it cosumes memory for storing the objects. We can access the list again because it's stored in memory.

Generator python function to get first "n" even numbers

def even_numbers(n):
  for i in range(1, n):
    yield i * 2
# Excecution
num_gen = even_numbers(3)
for num in num_gen:
  print(num)
# Output:
2
4
print(list(num_gen))
# Output: []

When we call above function it will return a generator object. As we discussed generator will produce the values on fly and it will not be available once its retrieved. If we the last "print" statement in above code. We got empty list after type conversion to list, Because we have used all the available values in the generator. This is the reason generators are faster than lists.

References:

https://docs.python.org/3/glossary.html#term-generator

Read Next: signup or sign-in using google to django application

Read Prev: understanding of python slice notation

Blog Archive