numpy.asarray — NumPy v2.6.dev0 Manual

numpy.asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)

#

Convert the input to an array.

Parameters:aarray_likeInput data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

dtypedata-type, optionalBy default, the data-type is inferred from the input data.

order{‘C’, ‘F’, ‘A’, ‘K’}, optionalThe memory layout of the output. ‘C’ gives a row-major layout (C-style), ‘F’ gives a column-major layout (Fortran-style). ‘C’ and ‘F’ will copy if needed to ensure the output format. ‘A’ (any) is equivalent to ‘F’ if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to ‘C’. Unlike ‘C’ or ‘F’, ‘A’ does not ensure that the result is contiguous. ‘K’ (keep) is the default and preserves the input order for the output.

devicestr, optionalThe device on which to place the created array. Default: None. For Array-API interoperability only, so must be "cpu" if passed.

Added in version 2.0.0.

copybool, optionalIf True, then the object is copied. If None then the object is copied only if needed, i.e. if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.). For False it raises a ValueError if a copy cannot be avoided. Default: None.

Added in version 2.0.0.

likearray_like, optionalReference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

Added in version 1.20.0.

Returns:outndarrayArray interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.

Examples

Convert a list into an array:

>>> a=[1,2]>>> importnumpyasnp>>> np.asarray(a)array([1, 2])Existing arrays are not copied:

>>> a=np.array([1,2])>>> np.asarray(a)isaTrueIf

dtype

is set, array is copied only if dtype does not match:

>>> a=np.array([1,2],dtype=np.float32)>>> np.shares_memory(np.asarray(a,dtype=np.float32),a)True>>> np.shares_memory(np.asarray(a,dtype=np.float64),a)FalseContrary to

asanyarray

, ndarray subclasses are not passed through:

>>> issubclass(np.recarray,np.ndarray)True>>> a=np.array([(1.,2),(3.,4)],dtype='f4,i4').view(np.recarray)>>> np.asarray(a)isaFalse>>> np.asanyarray(a)isaTrue