How to create a generator in Python?

Table of Contents

Introduction

A generator in Python is a special type of iterator that generates values one at a time as they are requested, using the yield keyword. Generators allow you to create memory-efficient iterators, which is particularly useful when handling large datasets or sequences. In this article, you’ll learn how to create a generator in Python through generator functions and generator expressions, along with examples.

Creating a Generator Function in Python

What is a Generator Function?

A generator function in Python is similar to a normal function, but instead of returning a single value and terminating, it uses the yield keyword to return a value and pause execution. Each time the generator is called, it resumes from where it left off, producing values one by one.

Syntax of a Generator Function

Here’s how to define a simple generator function using yield:

This generator function yields three values: 1, 2, and 3. To use the generator, you create a generator object and iterate over it.

Example of Using a Generator Function

Output:

In this example, the generator function my_generator() yields values one at a time. The generator object gen can be used in a loop to access each value sequentially.

Practical Use of Generators

Example: Generator for Fibonacci Sequence

You can use a generator to create an infinite or long sequence, such as the Fibonacci sequence.

Output:

In this example, the fibonacci() generator function yields an infinite sequence of Fibonacci numbers. You can use next() to access each value individually or iterate over it with a loop.

Generator Expressions in Python

In addition to generator functions, Python also supports generator expressions, which are a more concise way to create generators. They look similar to list comprehensions but use parentheses () instead of square brackets [].

Syntax of a Generator Expression

This generator expression produces the squares of numbers from 0 to 4. Generator expressions are often used in place of list comprehensions when working with large datasets or streams of data.

Example of Using a Generator Expression

Output:

In this example, the generator expression (x**2 for x in range(5)) lazily produces squares of numbers from 0 to 4.

Conclusion

Creating generators in Python is straightforward, either through generator functions using the yield keyword or generator expressions for more concise implementations. Generators allow for memory-efficient iteration over data, which is particularly useful when dealing with large datasets, infinite sequences, or streams of data. By generating values on demand, they can significantly reduce memory usage and improve performance in Python applications.

Similar Questions