Creating Arrays

The ndarray is NumPy's core object: a fast, fixed-type grid of numbers.

Syntaxnp.array([1, 2, 3])

NumPy gives Python the ndarray — an N-dimensional array of numbers that is far faster and more memory-efficient than a list.

Ways to make an array

  • np.array([...]) from a Python list.
  • np.zeros, np.ones, np.full for filled arrays.
  • np.arange and np.linspace for ranges.

Unlike a list, every element in an array shares one data type (dtype), which is what makes it fast.

Example

Example · python
import numpy as np

a = np.array([1, 2, 3, 4])
zeros = np.zeros(3)
range_ = np.arange(0, 10, 2)
line = np.linspace(0, 1, 5)

print(a)       # [1 2 3 4]
print(zeros)   # [0. 0. 0.]
print(range_)  # [0 2 4 6 8]
print(line)    # [0.   0.25 0.5  0.75 1.  ]
print(a.dtype) # int64

When to use it

  • A machine learning engineer converts a Python list of house prices into a numpy array to enable fast vectorised preprocessing before model training.
  • A scientist creates a zeros array to initialise a weight matrix before manually implementing gradient descent in a custom neural network.
  • A data pipeline uses np.arange to generate evenly spaced time steps for a time-series simulation dataset.

More examples

Array from a Python list

Creates a 1D numpy array from a plain Python list and shows its inferred float data type.

Example · python
import numpy as np

prices = np.array([120.5, 135.0, 98.3, 210.7])
print(prices)
print(prices.dtype)

Built-in array constructors

Demonstrates four common constructors: zeros, ones, arange (step-based range), and linspace (evenly spaced floats).

Example · python
import numpy as np

zeros = np.zeros((3, 4))
ones  = np.ones((2, 2))
rng   = np.arange(0, 10, 2)
linsp = np.linspace(0, 1, 5)

print(zeros)
print(ones)
print(rng)
print(linsp)

2D weight matrix initialisation

Creates weight and bias arrays for a neural-network layer using zeros and ones, plus an identity matrix with np.eye.

Example · python
import numpy as np

# Simulate a weight matrix for a 4-input, 3-neuron layer
W = np.zeros((3, 4))
b = np.ones(3)

# 2D identity for square operations
I = np.eye(4)
print(W.shape, b.shape, I.shape)

Discussion

  • Be the first to comment on this lesson.