| by Arround The Web | No comments

Python Generator

Sometimes we need to construct a large/infinite sequence of values, such as numbers, strings, or objects without absorbing too much memory. To accomplish this, the generator function is used in Python. This function returns an object named “generator” which can be iterated over to yield a series of values.

The below contents will be followed in this guide:

What is the Python Generator Function?

The generator function is a function that utilizes the “yield” keyword as an alternative to the “return” to retrieve a value. The “yield” keyword pauses the exception of the function and retrieves the present value of the caller. The function can be resumed from where it left off by calling/accessing the next() method on the generator object or utilizing a for loop. The generator object is an iterator that consists of two methods “__iter__()” and “__next__()” method.

How to Create/Construct a Generator Function?

To construct a generator function, follow the below steps:

  • Firstly, define/declare the function “my_generator” with the “def” keyword.
  • Next, we can utilize the “yield” statement instead of the “return” statement to generate the generator value.
  • After that, the generator function is accessed/called, but it does not run the function body instantly. Instead, it yields a generator object that can be looped over to generate the values.
  • We can utilize the “next()” function to iterate over the generator object to retrieve the result.

Here is an example:

def my_generator(n):
    value = 0

    while value < n:
        yield value
        value += 1

gen = my_generator(5)
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))

This code generated the following output:

Using for Loop with Generator Function

We can also utilize the “for loop” to iterate over the generator object instead of the “next()” method. Take this code as an example:

def my_generator(n):
    value = 0

    while value < n:
        yield value
        value += 1

gen = my_generator(5)
for num in gen:
    print(num)

This code shows below output:

We can also utilize the generator function with multiple yield values in the below code:

def func():

    yield 45
    yield 65
    yield 79

z = func()
for i in z:
    print(i)

Output

Python Generator Expression

We can also create the generator object in Python by using the Python generator expression. The generator expression is like a list comprehension, but it does not create/construct a list, it constructs a generator. The following code shows the generator expression syntax:

(expression for variable in iterable/sequence [if condition])

Here, the “expression” is the value to be yielded by the generator, the “variable” specifies the loop variable, and the “Iterable” is any object that can be looped/iterated through.

In the below example code, the generator expression is used to generate the squares of the first ten natural numbers:

gen = (x**2 for x in range(1, 11))
print(gen)
print(type(gen))

for i in gen:
    print(i)

Here is the output:

Difference Between Generator Functions and Regular/Simple Functions

In Python, the generator function utilizes the yield keyword to retrieve values, while the regular function uses the return keyword. The generator function retrieves the generator object that can be iterated over, while the simple function retrieves the single value or collections of values. In Python, generator functions can maintain their state between calls, while regular functions lose their state after returning.

Conclusion

In Python, the generator function is utilized to construct and process large/infinite value sequences without absorbing too much memory. To create a generator function, we need to define the simple function and generate the value using the yield keyword. Next, we create the object and iterate over it using the next() or for loop. This guide explored the Python generator function with multiple examples.

Share Button

Source: linuxhint.com

Leave a Reply