w3resource

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:

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.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to generate an array from a generator that yields 15 consecutive integers.
  • Create a function that utilizes a Python generator to produce a NumPy array and verifies its content and length.
  • Implement a solution that uses generator expressions and np.fromiter to build an array of specified length.
  • Test the generator-based array creation with different ranges to ensure it adapts dynamically.

Go to:


PREV : Check if a 2D array has null columns.
NEXT : Insert zeros between elements in an array.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.