Last updated

Creating Arrays

Definition: You can build a NumPy array from a Python list, or use built-in helpers that generate common arrays for you.

Example 1 — from a list

import numpy as np
a = np.array([1, 2, 3])
print(a)
b = np.array([[1, 2, 3], [4, 5, 6]])   # 2D array
print(b)

Example 2 — generator helpers

import numpy as np
print(np.zeros(3))        # [0. 0. 0.]
print(np.ones((2, 2)))    # 2x2 of ones
print(np.full(3, 7))      # [7 7 7]
print(np.arange(0, 10, 2))# [0 2 4 6 8]
print(np.linspace(0, 1, 5)) # 5 evenly spaced 0..1

When to use which

  • arange(start, stop, step) — like Python range, but an array
  • linspace(start, stop, count) — exactly N evenly spaced values
  • zeros / ones — handy starting points you fill in later

💡 Tip: a 2D array is just a list of lists — the inner lists become the rows.

Try it Yourself
Output

          
Ad · responsive