numpy.array()
The numpy.array()
is a commonly used function in the NumPy library of Python language. It returns a new array by converting input data (listed in different formats) into a NumPy array.
Syntax
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
object
: Input data, it can be a list, tuple, scalar or any other sequence of values that can be converted to an array.dtype
: Desired data type of array, optional.copy
: If True, the returned array is a new copy of input data.order
: Specifies the memory layout of the array. Default value is 'K' which means if input is in Fortran order, output array will also be in Fortran order. For C/C++ compatible order, pass 'C'.subok
: If True, then subclass of input argumentobject
will be passed through. Default is False.ndmin
: Specifies minimum number of dimensions of the output array.
Example
import numpy as np
# Create an array from a list/set of values
mylist = [1, 2, 3, 4]
arr1 = np.array(mylist)
print(arr1) # Output: [1 2 3 4]
# Create a multi-dimensional array
mylist2 = [(1,2,3), (4,5,6)]
arr2 = np.array(mylist2)
print(arr2) # Output: [[1 2 3][4 5 6]]
# Create an array of zeros
arr3 = np.zeros((2,3))
print(arr3) # Output: [[0. 0. 0.][0. 0. 0.]]
# Create an array of ones
arr4 = np.ones((2,3))
print(arr4) # Output: [[1. 1. 1.][1. 1. 1.]]
Output
[1 2 3 4]
[[1 2 3]
[4 5 6]]
[[0. 0. 0.]
[0. 0. 0.]]
[[1. 1. 1.]
[1. 1. 1.]]
Explanation
The numpy.array()
function creates an array from given input data like a list, tuple or a scalar value. It is also used to create arrays of all zeros or all ones. The output of this function is a NumPy array object.
Use
The numpy.array()
function is used to create NumPy arrays from input data like a list, set, tuple or scalar value.
Important Points
- The
numpy.array()
function creates a shallow copy of the input data. - If
dtype
is not provided, data type of the input data is used. - The
numpy.ndarray
class is the base class of all array types in NumPy. - In case of a multi-dimensional array, all sublists should be of equal length.
Summary
The numpy.array()
function is an important function of NumPy library in Python, which is used to create NumPy arrays from input data. The output is a new array object with necessary dimensions and data type, which can be further used for different computations.