Skip to content

NumPy Array Creation

Creating arrays from Python objects

From a list

from-list
import numpy as np
 
arr = np.array([1, 2, 3, 4])
print(arr)
print(type(arr))
from-list
import numpy as np
 
arr = np.array([1, 2, 3, 4])
print(arr)
print(type(arr))

From a nested list (2D)

from-nested
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
print(matrix)
print(matrix.shape)   # (2, 3)
from-nested
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
print(matrix)
print(matrix.shape)   # (2, 3)

From a tuple

from-tuple
arr = np.array((10, 20, 30))
print(arr)
from-tuple
arr = np.array((10, 20, 30))
print(arr)

Using built-in constructors

np.zeros()np.zeros()

Create an array filled with zeros.

zeros
arr = np.zeros((2, 3))
print(arr)
zeros
arr = np.zeros((2, 3))
print(arr)

np.ones()np.ones()

ones
arr = np.ones((3, 2))
print(arr)
ones
arr = np.ones((3, 2))
print(arr)

np.full()np.full()

Create an array filled with a constant value.

full
arr = np.full((2, 2), 7)
print(arr)
full
arr = np.full((2, 2), 7)
print(arr)

np.eye()np.eye() (identity matrix)

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

np.arange()np.arange() (range with step)

Similar to Python range()range(), but returns a NumPy array.

arange
arr = np.arange(0, 10, 2)
print(arr)  # [0 2 4 6 8]
arange
arr = np.arange(0, 10, 2)
print(arr)  # [0 2 4 6 8]

np.linspace()np.linspace() (even spacing)

Creates numnum values between start and stop.

linspace
arr = np.linspace(0, 1, 5)
print(arr)  # [0.   0.25 0.5  0.75 1.  ]
linspace
arr = np.linspace(0, 1, 5)
print(arr)  # [0.   0.25 0.5  0.75 1.  ]

Specifying dtype during creation

dtype
arr = np.array([1, 2, 3], dtype=np.float64)
print(arr)
print(arr.dtype)
dtype
arr = np.array([1, 2, 3], dtype=np.float64)
print(arr)
print(arr.dtype)

Quick recap: which function to use?

  • np.array(...)np.array(...) → convert existing data (lists)
  • np.zeros(shape)np.zeros(shape) / np.ones(shape)np.ones(shape) → initialize arrays
  • np.full(shape, value)np.full(shape, value) → constant arrays
  • np.eye(n)np.eye(n) → identity matrix
  • np.arange(start, stop, step)np.arange(start, stop, step) → integer sequences
  • np.linspace(start, stop, num)np.linspace(start, stop, num) → precise evenly spaced floats

Next

Continue to: NumPy Data Types (dtypes) to learn how dtypes affect memory, performance, and numeric precision.

🧪 Try It Yourself

Exercise 1 – Create a NumPy Array

Exercise 2 – Array Shape and Reshape

Exercise 3 – Array Arithmetic

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did