numpy.fromiter() function – Python

Last Updated : 25 Mar, 2026

fromiter() function creates a NumPy array from any iterable. It is useful for converting data from sources like generators or files into an array for further processing.

Syntax:

numpy.fromiter(iterable, dtype, count = -1)

Parameters:

  • iterable: The iterable object providing data for the array.
  • dtype: [data-type] Data-type of the returned array.
  • count: [int, optional] Number of items to read.

Returns: [ndarray] The output array.

Numpy.fromiter() function creates a Numpy array from an iterable object. where each element is converted and stored in the array. Here is an example of to use 'numpy.fromiter()':

Python
import numpy as np

my_iterable=[1,2,3,4,5,6]
my_array=np.fromiter(my_iterable,dtype=int)
print(my_array)

Output
[1 2 3 4 5 6]

Example 1: Using the numpy.fromiter() function to create a NumPy array from an iterable generated by a generator expression.

Python
import numpy as geek

iterable = (x**3 for x in range(4))
gfg = geek.fromiter(iterable, int)
print (gfg)

Output
[ 0  1  8 27]

Example 2: The NumPy array gfg containing the elements generated by the generator expression. In this case, it's the squares of the numbers from 0 to 5.

Python
import numpy as geek

iterable = (x * x for x in range(6))
gfg = geek.fromiter(iterable, float)
print (gfg)

Output
[ 0.  1.  4.  9. 16. 25.]

To create a Numpy array from Unicode charcters using 'numpy.froiter()', you can pass an iterable of Unicode strings as input.Each Unicode string can be represented using its corresponding code point.

Python
import numpy as np

unicode = [71, 101, 101, 107]
array = np.fromiter((chr(x) for x in unicode), dtype='U1')
print(array)

Output
['G' 'e' 'e' 'k']

In Numpy the 'U2' data type reprsents Unicode strings with a fixed length of 2 characters.The 'U' indicates that the data type in Unicode, and the number '2' specifies the length of each string.

Here's an example of to use 'U2' in numpy:

Python
import numpy as np

a = "python"
b = np.fromiter(a, dtype='U2')
print(b)

Output
['p' 'y' 't' 'h' 'o' 'n']
Comment