NumPy asarray()

The asarray() method converts all array_like objects into an array.


asarray() Syntax

The syntax of asarray() is:

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

asarray() Argument

The asarray() method takes the following arguments:

  • a- any array_like input object
  • dtype(optional)- type of output array(dtype)
  • order(optional)- specifies the order in which the array elements are placed
  • like(optional)- reference object to allow the creation of non-NumPy arrays

asarray() Return Value

The asarray() method returns an array representation of a.


Example 1: Convert to an Array Using asarray

Output

[1 2 3 4 5]
['1' '2' '3' '4' '5']

Note: Using the dtype argument specifies the data type of the resultant array.


Key Difference Between np.array() and np.asarray()

Both np.array() and np.asarray() are NumPy functions used to generate arrays from array_like objects but they have some differences in their behavior.

The array() method creates a copy of an existing object whereas asarray() creates a new object only when needed.

Let us see an example.

Output

Using array(): False
Using asarray(): True