Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

NumPy asarray() function

In this tutorial, we will cover numpy.asarray() function of the Numpy library.

The numpy.asarray() function in Numpy is used to convert the input or any existing data into an array.

  • The existing data can be in the form of Lists, Tuples, tuples of tuples, list of tuples, tuples of lists, etc.

  • In case if you want to convert any python sequence into the Numpy array object i.e ndarray then this function is helpful for you.

Syntax of numpy.asarray():

Given below is the basic syntax to use this function:

numpy.asarray(sequence,  dtype, order)  

Parameters:

Let us discuss the parameters mentioned above for the asarray() function:

  • sequence
    This parameter is used to indicate the input data that can be in any form and is to be converted into an array. This parameter includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

  • dtype
    This parameter is used to indicate the data type of each item of the array. It is an optional parameter with default value None.

  • order
    This parameter is used to indicate the memory representation that is whether to use row-major (C-style) or column-major (Fortran-style) The default value is set to 'C'.

Returned Values:

This function will return an array with all the values from the sequence used to create the array. If the input is already an ndarray with matching dtype and order then this function will not create any copy.

Now it's time to take a look at some examples of this function.

Example 1:

In the code snippet given below we will convert a Python list into an array:

import numpy as np

mylist = [1, 2,4,5,8,10]
np.asarray(mylist)


array([ 1, 2, 4, 5, 8, 10])

Example 2:

In the code snippet below we will create a NumPy array from a Python tuple:

import numpy as np  

inp = (10,9,1,2,3,4,5,6,7,8)     
a = np.asarray(inp); 
print("The output is:")
print(a)  
print("The datatype of output is:")
print(type(a))  


The output is:
[10 9 1 2 3 4 5 6 7 8]
The datatype of output is:
<class 'numpy.ndarray'>

Example 3:

In the code snippet given below we will create an array using more than one list:

import numpy as np  

l = [[1,2,3,4,5,6,7],[8,9],[12,34,45]]  
a = np.asarray(l);
print("The data type of output is:")
print(type(a))  
print("The output array is:")
print(a)  


The data type of output is:
<class 'numpy.ndarray'>
The output array is:
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9]) list([12, 34, 45])]

Summary

This tutorial covered the numpy.asarray() mathematical function in the Numpy library which is used to create Numpy ndarrya using various different Python sequence like Lists, Tuple, etc.