Python Generators

Table Of Contents:

  1. What Is Generator In Python?
  2. How To Create A Generator?
  3. Examples Of Generators.
  4. Advantages Of Using Generators.

(1) What Is Generator In Python?

  • The problem with iterators like list, set, tuple and dictionary is that they are too slow to fetch values from them.
  • To solve this problem we have ‘Generators’ in Python.
  • Generators help us to retrieve elements from the iterators like list, set, tuple and dictionary much faster ways, as compared to traditional using a ‘for’ loop to iterate.

(2) How To Create A Generator In Python?

  • The first step of creating a ‘Generator’ is to define your own user-defined function.
  • ‘Generators’ are basically user-defined functions with one twist.
    The twist is that normal functions use the ‘return’ keyword to return some value, but the ‘Generator’ function uses the ‘yield’ keyword to return some value.
  • With the use of the ‘yield’ keyword, you are making the normal function into the ‘Generator’ function.
  • By making the function to ‘Generator’ function you are also making it an ‘iterable’ object.
  • That means you can iterate over the ‘Generator’ function.
  • You need to use the next() method to iterate over the ‘Generator’ function object.

(3) Examples Of Generator In Python?

Example: Without Generators

import time

lst = [i for i in range(100000)]
start_time = time.time()
print('Start:',start_time)

for i in lst:
    print(i)
    
end_time =  time.time()
print('End:',end_time)

print(f"Iteration:Time taken: {(end_time-start_time)*10**3:.03f}ms")
Output:
[0,1,2,3,.........99999]
Iteration:Time taken: 5416.487ms

Explanation:

  • Here I have a list containing elements from 0 to 100000.
  • To iterate over the list I have used the ‘for’ loop.
  • It took me around 5416.487 milliseconds to iterate over the list.

Example: With Generators

List To Iterate:

lst = [i for i in range(100000)]

Generator Method:

def myFunc():
    yield lst

Iterating Generator Method:

import time
start_time = time.time()
print('Start:',start_time)

print(next(myFunc()))

end_time = time.time()
print('End:',end_time)
print(f"Iteration:Time taken: {(end_time-start_time)*10**3:.03f}ms")
Output:
[0,1,2,3,.........99999]
Iteration:Time taken: 13.927ms

Explanation:

  • Here I have a list containing elements from 0 to 100000.
  • First I have created a ‘Generator’ function called myFunc(), which will return a list, using the ‘yield’ keyword.
  • To iterate over the list I have used the ‘next’ function.
  • It took me only 13.927 milliseconds to iterate over the list.

(4) Advantages Of Using Generator In Python?

  • Generators allow you to create iterators in a very user-defined manner.
  • Iterators allow lazy evaluation, only generating the next element of an iterable object when requested. This is useful for very large data sets.
  • Generators are much faster than Iterators while accessing the elements.
  • Iterators and generators can only be iterated over once.
  • Generator Expressions are better than Iterators (for simple cases only).

Leave a Reply

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