NumPy Arrays are the heart of the NumPy library. They are powerful, flexible, and optimized for numerical operations. Unlike Python lists, NumPy arrays are faster, memory-efficient, and support vectorized operations.
A NumPy array (also called ndarray
) is a grid of values, all of the same type, and indexed by a tuple of non-negative integers.
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4])
print(arr)
Output:
[1 2 3 4]
# 1D array
a = np.array([10, 20, 30])
# 2D array
b = np.array([[1, 2], [3, 4]])
# 3D array
c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
Every array has attributes that give you more information:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3)
print(arr.ndim) # 2
print(arr.size) # 6
print(arr.dtype) # int64 (depends on system)
np.zeros((2, 3)) # 2x3 array of zeros
np.ones((3, 2)) # 3x2 array of ones
np.eye(3) # Identity matrix
np.arange(0, 10, 2) # [0 2 4 6 8]
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
NumPy allows element-wise operations without looping.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2) # [5 7 9]
print(arr1 * arr2) # [4 10 18]
print(arr1 ** 2) # [1 4 9]
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!