In Python, numpy.array()
is a function provided by the NumPy library to create arrays, which are more efficient for numerical operations than Python’s native lists. The numpy.array()
function can create an array from a variety of input types like lists, tuples, and other sequences.
Here’s a basic example of how to use numpy.array()
:
import numpy as np
# Creating a numpy array from a list
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Key Features of numpy.array()
:
- Multidimensional Arrays: You can create multidimensional arrays (matrices) as well.
arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr)
- Array Data Types: NumPy arrays support various data types, such as integers, floats, and complex numbers. You can specify the data type using the
dtype
argument.arr = np.array([1.1, 2.2, 3.3], dtype=np.float32) print(arr)
- Shape and Size: The
.shape
and.size
attributes allow you to view the dimensions and total number of elements in the array.print(arr.shape) # Output: (2, 3) for a 2x3 matrix print(arr.size) # Output: 6
- Default Data Type: If you don’t specify a data type, NumPy tries to infer the most appropriate one, usually converting all elements to the highest type (e.g., float64 for mixed integer and float input).
Example:
import numpy as np
# 1D Array
arr_1d = np.array([1, 2, 3, 4])
print(arr_1d)
# 2D Array (Matrix)
arr_2d = np.array([[1, 2], [3, 4]])
print(arr_2d)
# Array with dtype specified
arr_float = np.array([1, 2, 3], dtype=np.float64)
print(arr_float)
Output:
[1 2 3 4]
[[1 2]
[3 4]]
[1. 2. 3.]
In summary, numpy.array()
is an efficient and versatile way to work with arrays, particularly for numerical operations, in Python.