w3resource

NumPy: Create an array using generator function that generates 15 integers

NumPy: Array Object Exercise-184 with Solution

Write a NumPy program to create an array using generator function that generates 15 integers.

Pictorial Presentation:

Python NumPy: Create an array using generator function that generates 15 integers

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Defining a generator function 'generate' that yields numbers from 0 to 14
def generate():
   for n in range(15):
       yield n

# Creating a NumPy array 'nums' using 'fromiter' by converting the generator into a NumPy array of type 'float'
nums = np.fromiter(generate(), dtype=float, count=-1)

# Displaying the newly created array 'nums'
print("New array:")
print(nums)

Sample Output:

New array:
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14.]

Explanation:

In the above code -

def generate():: Defines a function "generate".

for n in range(15):: Iterates over a range of numbers from 0 to 14.

yield n: Yields the current number n during each iteration.

nums = np.fromiter(generate(),dtype=float,count=-1): This line creates a NumPy array “nums" from the values generated by the generate() function. The dtype=float argument specifies that the resulting array should have the float data type. The count=-1 argument specifies that all items generated should be included in the array.

Python-Numpy Code Editor:

Previous: Write a Numpy program to test whether a given 2D array has null columns or not.
Next: Write a Numpy program to create a new vector with 2 consecutive 0 between two values of a given vector.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-184.php