NumPy Creating Arrays

NumPy Tutorial

NumPy Creating Arrays

In NumPy Creating Arrays is the first and most important step because almost all operations are performed on arrays. NumPy provides multiple ways to create arrays depending on your use case.

Before starting, always import NumPy:

import numpy as np

 1. Creating an Array from a Python List

1D Array



 

2D Array (Matrix)



 

3D Array



 


2. Creating Arrays with Default Values

np.zeros() – Array filled with zeros

a = np.zeros(5) # 1D
b = np.zeros((2, 3)) # 2D
print(a)
print(b)

np.ones() – Array filled with ones

a = np.ones(4)
b = np.ones((3, 2))
print(a)
print(b)

np.full() – Array filled with a specific value

a = np.full((2, 3), 7)
print(a)

3. Creating Arrays with a Range of Numbers

np.arange() – Similar to Python range()

a = np.arange(1, 10)
b = np.arange(1, 10, 2)
print(a)
print(b)

np.linspace() – Evenly spaced values

a = np.linspace(0, 1, 5)
print(a)

👉 Best for scientific & mathematical calculations


4. Creating Identity & Diagonal Matrices

np.eye() – Identity matrix

a = np.eye(3)
print(a)

np.diag() – Diagonal matrix

a = np.diag([1, 2, 3])
print(a)

5. Creating Random Arrays

np.random.rand() – Random values (0 to 1)

a = np.random.rand(3)
b = np.random.rand(2, 2)
print(a)
print(b)

np.random.randn() – Random values (normal distribution)

a = np.random.randn(3)
print(a)

np.random.randint() – Random integers

a = np.random.randint(1, 10, size=(2, 3))
print(a)

6. Creating Arrays Like Another Array

np.zeros_like()

x = np.array([1, 2, 3])
y = np.zeros_like(x)
print(y)

np.ones_like()

y = np.ones_like(x)
print(y)

7. Creating an Empty Array

np.empty() (contains garbage values)

a = np.empty((2, 3))
print(a)

⚠️ Use only when performance is critical


 8. Checking Array Properties

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr.shape) # dimensions
print(arr.ndim) # number of dimensions
print(arr.size) # total elements
print(arr.dtype) # data type


Summary Table

FunctionPurpose
np.array()Create from list
np.zeros()Zeros array
np.ones()Ones array
np.full()Fixed value
np.arange()Range
np.linspace()Even spacing
np.eye()Identity matrix
np.random.*Random arrays

You may also like...