Python

How to Create and Use Python Generators

While working as a developer, you often need to work with many insignificant data values. Storing those values consumes a chunk of memory, reducing the efficiency of your code. However, in Python, you can use generators to avoid that loss.

With generators, you can mass-produce the values of a particular sequence without storing them altogether in the memory. Moreover, the “generator” function creates an object which generates values when it is iterated over. So, if you want to get your hands on Python generators, this tutorial is for you. Here, we will explain how to create and use the Python generators.

How to Create and Use the Python Generators

Python generators are used to work on the data sequences effectively, mainly when dealing with large or nearly endless datasets. The benefits of Python generators are:

  1. Concise: You can define the generators easily in a concise manner which improves the code readability.
  2. Memory Efficient: They generate a single value simultaneously which consumes less memory and improves efficiency.
  3. Built-in functions: In Python, generators have predefined functions like next(), iter(), and yield to ease their working.
  4. Pause and resume feature: While working on complex algorithms, you can use the “yield” function to pause and resume the operation of generators.

You can create and use generators in various ways in Python. We will further divide this section to demonstrate its implementation using different examples. First, let’s take a look at the basic syntax:

def func_name() :
    yield expression

The “def” defines a function, and “yield” is used to build the “generator” function. However, another method also helps to create a generator using only one-line expressions.

Generator Function to Yield a String

Let’s define a generator function to yield some value:

def generator():
    yield "This is a generator"
for value in generator():
    print(value)

When we iterate over it using a “for” loop, the program generates the specified values which you can print using the “print” function.

Generator Function to Make a Counter

The following program is the example for the generator function to generate a sequence of numbers:

def my_generator(n):
    counter = 0
    while counter < n:
        yield counter
        counter += 1
for counter in my_generator(10):
    print(counter)

For example, if the input is 10, you will get values from 0 to 9 upon compiling this code.

Fibonacci Series Using the Generator Function

Let’s now use the Fibonacci series which is the most basic series in programming:

def series_fibonacci(limit):
    i, j = 0, 1
    while i < limit:
        yield i
        i, j = j, i + j

a = series_fibonacci(6)

print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))

We will get the series as follows by running the code:

First, create an object named “a” and call the “generator” function with the desired input as an argument.

The next() keyword is a manual iterator. Each time we use next(a), it iterates over one value of “a”. However, we can use the “for” loop to print all the values of “a” at once as shown in the following example:

Using “for” loop instead of the next() function:

def series_fibonacci(limit):
    i, j = 0, 1
    while i < limit:
        yield i
        i, j = j, i + j

a = series_fibonacci(6)
for value in a :
    print(value)

The result of running the code won’t differ because it is an alternative method of writing the previous program:

What Are Generator Expressions in Python?

Python generator expressions are a way to create the “generator” functions concisely using linear expressions. Here is the simple syntax:

(expression for variable in iterable if condition)

For example, create a generator expression to calculate the squares of odd numbers from 0 to “n” when “n” is the input value.

odd_squares = (x * x for x in range(10) if x % 2 != 0)
for value in odd_squares:
    print(value)

The previous code yields the following result:

Conclusion

This is all about the different methods to create and use the Python generators. We explained everything about the Python generator expressions. You should use these expressions if you consider using generators in any of your projects because they are more efficient in every programming aspect.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.