Python Generators

  • Python

In this tutorial, we’ll learn about Python Generators, how they are created and why do we use them.

In simple terms, python generators are simple functions that are used to create Iterators without defining __iter__() and __next__() methods that are handled by Python itself.

How to create a Generator?

Creating a Generator in python is as easy as replacing the return statement by yield. Let’s understand the syntax using a simple comparison.

A regular function :

def name():
  return "Techie"

A Generator :

def name_gen():
  yield "Techie"

Both return and yield will give us the same output if we print it but notice when try to print the name.

def name():
  return "Techie"

def name_gen():
  yield "Techie"

obj1 = name()
obj2 = name_gen()

print(obj1)
print(next(obj2))

Output :

Techie
<generator object name_gen at 0x7fcf20159cf0>

This gives us an output that there is a generator object at xyz location.

We know how to access values in an Iterator is by using the next() method. Let’s check it out.

def name():
  return "Techie"

def name_gen():
  yield "Techie"

obj1 = name()
obj2 = name_gen()

print(obj1)
print(next(obj2))

Output :

Techie
Techie

Let’s understand this using another example where we’ll fetch first five values.

def FirstFive():
  x = 1
  while x <= 5:
    yield x
    x += 1

result = FirstFive()

for i in result:
  print(i)

Output :

1
2
3
4
5

Why do we use generators?

Let’s understand this by taking a situation where you to fetch thousands of values from a database and you create a function to perform that. Now, that function will store the entire set of values in the memory before printing it.

Generators on the other hand will access elements one at a time instead of loading all of the to the memory at once which will in return save memory.

Also, Generators are easy to implement where to create Iterators, we need to define __iter__() and __next__() methods.