Generator function to create array values

Generator functions are a powerful tool in Python for generating sequences of values on-the-fly, without having to precompute and store them all in memory. In this thread, you will learn how to make generator function that produces 10 random integers and then use NumPy to build an array from those values. There are several ways to create a generator function that generates n integers. Here are a few examples.

1. By "while" loop:

We can define the generator function, which uses a while loop. Inside the loop, the yield keyword is used to return the current value of i. We then call the built-in list() function to store values and then convert this list into NumPy array.

In the above code, We import NumPy library and give it the alias np. We use np.array() function to create an array and use the generator function as a parameter, that help to create a list of elements.

2. By "for" loop :

We can also define the generator function, which uses a for loop. Inside the loop, the yield keyword is used to return the current value of i. We then call the built-in list() function to store values and then convert this list into NumPy array.

In the above code, after importing NumPy library and giving it the alias np. We use np.array() function to create an array and use the generator function as a parameter, that help to create a list of elements.

3. By "generator expression":

In this implementation, we uses a generator expression, which is a more concise way of creating a generator. The generator expression is similar to a list comprehension, but instead of returning a list of values, it returns a generator that yields values on-the-fly.

In the above code, We import NumPy library and give it the alias np. We use np.array() function to create an array and use the generator function as a parameter, that help to create a list of elements.