Numpy array VS Numpy asarray

In Python, NumPy array and NumPy asarray are used to convert the data into ndarray. If we talk about the major difference that is when we make a NumPy array using np.array, it creates a copy of the object array or the original array and does not reflect any changes made to the original array. Whereas on the other hand, when we try to use NumPy asarray, it would reflect all the changes made to the original array.

Example 

Here we can see that copy of the original object is created which is actually changed and hence it’s not reflected outside. Whereas, in the next part, we can see that no copy of the original object is created and hence it’s reflected outside.

Python3




import numpy as np
 
# creating array
a = np.array([ 2, 3, 4, 5, 6])
print("Original array : ",a)
 
# assigning value to np.array
np_array = np.array(a)
a[3] = 0
print("np.array Array : ",np_array)
 
# assigning value to np.asarray
np_array = np.asarray(a)
print("np.asarray Array : ",np_array)


Output:

Original array :  [2 3 4 5 6]

np.array Array : [2 3 4 5 6]
np.asarray Array : [2 3 4 0 6]


Difference between np.asarray() and np.array()?

NumPy is a Python library used for dealing with arrays. In Python, we use the list inplace of the array but it’s slow to process. NumPy array is a powerful N-dimensional array object and is used in linear algebra, Fourier transform, and random number capabilities. It provides an array object much faster than traditional Python lists.

Similar Reads

np.array in Python

The np.array() in Python is used to convert a list, tuple, etc. into a Numpy array....

Creating a NumPy array using the .array() function

Python3 # importing numpy module import numpy as np   # creating list l = [5, 6, 7, 9]   # creating numpy array res = np.array(l)   print("List in python : ", l)   print("Numpy Array in python :", res) print(type(res))...

np.asarray in Python

...

Convert a list into an array using asarray()

The numpy.asarray()function is used when we want to convert the input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays....

Numpy array VS Numpy asarray

Python3 import numpy as np l = [1, 2, 5, 4, 6]   print ("Input list : ", l)      res = np.asarray(l) print ("output array from input list : ", res) print(type(res))...