The asarray()
method in NumPy can be used to create an array from data that already exists in the form of lists or tuples.
numpy.asarray(a, dtype=None, order=None, *, like=None)
a
: Input data. a
can be in the form of a tuple, a list, a list of tuples, a tuple of tuples, or a tuple of lists.
dtype
: The data type to be applied to each element of the array. This parameter is optional. By default, the data type is inferred from a
.
order
: A memory layout that can be set as F
,C
,K
, or A
.
K
and A
depend on the order of a
.F
is a column-major representation, and C
is a row-major memory representation.C
.like
: like
allows arrays that are not NumPy arrays to be created. This parameter is optional. The default value of the parameter is None
.
The function returns an array.
import numpy as np#create numpy arrays from listslist1=[5, 3, 6, 2, 1, 5]list2=[10, 3, 32, 95, 12, 34, 3]#print type of both listsprint("Type of list1: ", type(list1))print("Type of list2: ", type(list2))#create arrays from the listsarray1 = np.asarray(list1)array2 = np.asarray(list2)#print type of both arraysprint("Type of array1: ", type(array1))print("Type of array2: ", type(array2))
import numpy as np#create numpy arrays from tuplestuple1 = (43, 21, 32, 67, 21, 5)tuple2=(8, 6, 1, 0, 2, 1, 5)#print type of both tuplesprint("Type of tuple1: ", type(tuple1))print("Type of tuple2: ", type(tuple2))#create arrays from the tuplesarray1 = np.asarray(tuple1)array2 = np.asarray(tuple2)#print type of both arraysprint("Type of array1: ", type(array1))print("Type of array2: ", type(array2))
import numpy as np#create an numpy array from a list of tupleslist1 = [(3, 5),(6, 4, 8)]#print typeprint("Type of list1: ", type(list1))#create array from the list of tuplesarray1 = np.asarray(list1)#print typeprint("Type of array1: ", type(array1))