numpy.asarray() – The NumPy asarray Python Function

Introduction to NumPy asarray

When we wish to convert the input to an array, we utilize the numpy.asarray() function. Lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and arrays can all be used as input.

Syntax:

numpy.asarray(arr, dtype=None, order=None, *, like=None)

Parameters:

  • arr : [array_like] Input 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.
  • dtype : [data-type, optional] By default, the data-type is inferred from the input data.
  • order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.
  • like: [array_like] Reference object to allow the creation of arrays that are not NumPy arrays. If an array-like pass in as like supports the array_function protocol, the result will be define by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0.

Return: [ndarray] Array interpretation of arr. No copy is perform if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is return.

Code Examples of NumPy asarray

Example 01: List to array

# welcome to softhunt.net
# Python program explaining
# numpy.asarray() function

import numpy as np
my_list = [1, 2, 3, 4, 5, 6]

print ("Input list : ", my_list)

	
out_arr = np.asarray(my_list)
print ("output array from input list : ", out_arr)

Output:

Input list :  [1, 2, 3, 4, 5, 6]
output array from input list :  [1 2 3 4 5 6]

Example 02: Tuple to an array

# welcome to softhunt.net
# Python program explaining
# numpy.asarray() function

import numpy as np

my_tuple = ([1, 2, 3], [4, 5, 6])

print ("Input tuple : ", my_tuple)
	
out_arr = np.asarray(my_tuple)
print ("output array from input tuple : \n", out_arr)

Output:

Input tuple :  ([1, 2, 3], [4, 5, 6])
output array from input tuple : 
 [[1 2 3]
 [4 5 6]]

FAQs

What is the difference between np.array and np.asarray?

The main difference is that using np.array to build a NumPy array creates a duplicate of the object array rather than reflecting changes to the original array. When you use np.asarray, on the other hand, it will reflect changes to the original array.

What is the difference between Ndarray and array?

ndarray() is a class, while numpy.array() is a method / function to create ndarray .

Conclusion

That’s all for this article. If you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.squeeze() – The NumPy squeeze Python Function

Leave a Comment