NumPy Tutorial NumPy Statistics NumPy References

NumPy - array() function



The NumPy array() function is used to create a numpy array. A list, tuple or any array-like object can be passed as object parameter to convert it into a numpy array.

Syntax

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Parameters

object Required. Specify the collection object to be converted into ndarray. It can be list, tuple, set, dictionary etc.
dtype Optional. Specify the desired data type. It is used to change the data type of the array element.
copy Optional. Specify True to copy the object, False otherwise.
order Optional. Specify order. It can take four possible values.
  • 'C' - for C order (row major).
  • 'F' - for F order (column major).
  • 'A' - unchanged if copy=False. If copy=True, F and C order preserved.
  • 'K' - unchanged if copy=False. If copy=True, When the input is F and not C then F order otherwise C order.
subok Optional. Specify True to make the returned array sub-classes pass through. By default, the returned array forced to be base class array.
ndmin Optional. Specify the minimum dimension of the array.

Return Value

Returns an array object satisfying the specified requirements.

Example: Create 1-D Array

In the example below, a list is used to create a 1-D numpy array.

import numpy as np
MyList = [1, 2, 3, 4, 5]
npArray = np.array(MyList)
print(npArray)

The output of the above code will be:

[1 2 3 4 5]

Example: Create 2-D Array

In this example, a list of lists is used to create a 2-D numpy array.

import numpy as np
MyList = [[1, 2, 3], [4, 5, 6]]
npArray = np.array(MyList)
print(npArray)

The output of the above code will be:

[[1 2 3]
 [4 5 6]]

Example: Create 2-D Array using ndmin parameter

A n-dimensional array can be created using ndmin parameter of the array function. Like, in this example, it is used to create 2-D array.

import numpy as np
MyList = [1, 2, 3, 4, 5]
npArray = np.array(MyList, ndmin=2)
print(npArray)

The output of the above code will be:

[[1 2 3 4 5]]

Example: Create 1-D Array with dtype parameter

The dtype argument is used to change the data type of elements of the ndarray object.

import numpy as np
MyList = [1, 0, 0, 1, 0]
npArray = np.array(MyList, dtype=bool)
print(npArray)

The output of the above code will be:

[ True False False  True False]

❮ NumPy - Functions