Sequence generator in Python

In this tutorial, we will learn: sequence generator in Python.

Introduction:

A generator is a type of function which generates the sequence in python. In mathematics, we usually represent the sequence by allowing duplicate members. In computer science, we generate a sequence by array, list, set, tuple, etc. Here we use yield statement in the function. It is similar to normal function in python but takes some changes in statements inside the function. The advantage of using this is we don’t have to compute the entire series instead of this in generator one value waits until the next value is called. For example, if we have to call 1 million values from the list, one way is to call them one by one in for loop and the second way is to make a list and call them as peruses from memory. Usually, we use range() function in python which does not make a list in memory for all the values. Instead of this we can track the last number and provide all the numbers in a flow. If the user needs to use the list they have to use list() function to transform it from the generator.

Let’s explore some coding part of this topic and understand how to use yield in our function:

#A NORMAL FUNCTION T GET CUBES
def cube(n):
    result = []
    for x in range(n):
        result.append(x**3)
    return result
print(cube(8))
#THIS WILL MAKE A LIST FOR OUTPUT WHICH WILL TAKE A LOT OF MEMORY
#INSTEAD OF THIS WE CAN USE FOR LOOP TO PRINT ONE ELEMENT AT A TIME
for x in cube(10):
    print(x)

#TO MAKE THIS CODE SHORTER WE CAN USE YIELD IN THE FUNCTION
def cube(n):
    for x in range(n):
        yield x**3
        
for x in cube(10):
    print(x)
#NOW THE OUTPUT WILL PRINT ONE NUMBER AT A TIME WHICH WILL TAKE LESS AMOUNT OF MEMORY

Output:

The first output is:

[0, 1, 8, 27, 64, 125, 216, 343, 512]

The second output is:

0
1
8
27
64
125
216
343
512

The third output is:

0
1
8
27
64
125
216
343
512

In all three outputs, we can see that the third output is taking less memory and also fewer lines of code. Which is more efficient than the remaining two.

There are so many other examples of sequence generator are also available. Using lambda function, adding interval in for loop as the third parameter and using classes in python to use less memory space are some of the prime examples of these.

Also read:

Leave a Reply

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