NumPy: Create an array using generator function that generates 15 integers
Create array using generator function.
Write a NumPy program to create an array using generator function that generates 15 integers.
Pictorial Presentation:
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics