What is the numpy.fromiter() function in Python?

Overview

The fromiter() function in Python simply creates a new 1D (one-dimensional) array from an iterable object passed to the object.

Syntax

numpy.fromiter(iter, dtype)

Parameter value

The fromiter() function takes the following parameter values:

  • iter: This is the iterable object representing the data for the array.
  • dtype: This is the data type of the desired array.

Return value

The fromiter() function returns an output 1D array.

Code example

import numpy as np
# Creating an iterable object
myiterable = (i * i for i in range(3))
# Implementing the numpy.fromiter() function
myarray = np.fromiter(myiterable, float)
print(myarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an iterable array called myiterable.
  • Line 7: We implement the fromiter() function on the iterable array myiterable and assign the output to a myarray variable.
  • Line 9: We print myarray, the new 1D array.

Free Resources