Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 49 ยท Getting Started

Creating Arrays

Create NumPy arrays without typing every value: zeros, ones, full, arange, linspace, logspace, eye, diag, meshgrid, fromfunction, tile and repeat.

Typing out lists gets old fast. Real programs build arrays from rules: "a grid of zeros", "numbers from 0 to 100 in steps of 5", "100 evenly spaced points between 0 and 1". NumPy has a family of creation functions for these jobs, and you will use them constantly.

This lesson groups them by purpose: filled arrays, number ranges, identity-style matrices, grids, and repetition. Each function takes a shape (an int or a tuple) and an optional dtype. If you need a refresher on those words, see Your First Arrays.

Filled arrays: zeros, ones, full, empty

np.zeros, np.ones and np.full make arrays of a given shape and a fixed value. They default to float64 unless you pass a dtype.

Python zeros, ones and full

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

np.full takes its dtype from the fill value, so 7 gives integers and 7.5 gives floats.

np.empty allocates memory without setting it. It is a little faster, but the contents are whatever bytes were there before, so never print or use them until you have written real values.

Python
buffer = np.empty((3, 4))   # contents are unpredictable garbage
buffer[:] = 0               # always fill before reading

The *_like versions copy the shape and dtype from an existing array: np.zeros_like(a), np.ones_like(a), np.full_like(a, 9) and np.empty_like(a).

Python The _like functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Number ranges: arange, linspace, logspace

np.arange works like Python's range, but it returns an array and accepts floats. Its arguments are start, stop (excluded) and step.

np.linspace(start, stop, num) is different: you say how many points you want, and the end value is included by default. This is the right tool for plotting and for floating-point steps, because arange with a float step can produce a surprising number of elements due to rounding.

np.logspace(start, stop, num) gives numbers spaced evenly on a logarithmic scale: 10**start up to 10**stop.

Python arange, linspace and logspace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tip: Use arange for integer steps and linspace when you care about the exact number of points or about hitting the end value. np.arange(0, 1, 0.1) yields 10 numbers, but a tiny change in the step can add an eleventh.

Identity and diagonal matrices

np.eye(n) makes an n by n matrix with ones on the diagonal. It also accepts rectangular shapes and a diagonal offset k. np.identity(n) is the square-only shortcut. np.diag builds a diagonal matrix from a 1D array, or pulls the diagonal out of a 2D array.

Python eye, identity and diag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The identity matrix matters in linear algebra: multiplying by it changes nothing. Matrix Operations uses it again.

Grids: meshgrid and fromfunction

Sometimes you need the coordinates of every point on a grid, for example to evaluate a function of x and y everywhere. np.meshgrid takes 1D coordinate arrays and returns 2D arrays of x-values and y-values.

graph LR
    X["x = [0, 1, 2]"] --> M["np.meshgrid(x, y)"]
    Y["y = [0, 1]"] --> M
    M --> XX["XX: shape (2, 3)<br/>x repeated down the rows"]
    M --> YY["YY: shape (2, 3)<br/>y repeated across the columns"]

meshgrid turns two coordinate lists into two full grids of the same shape.

Python meshgrid and fromfunction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

np.fromfunction(f, shape) calls f once, passing whole index arrays (not one index at a time), so write f using array math, not if statements. By default the indices are floats, so pass dtype=int when you want integers.

Repetition: tile and repeat

np.tile(a, reps) repeats the whole array. np.repeat(a, n) repeats each element. They are easy to confuse, so compare them directly:

Python tile versus repeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does np.arange(2, 10, 3) return?

    arange starts at 2, steps by 3 and stops before 10: 2, 5, 8. The stop value is excluded.
  2. 2. How is np.linspace(0, 1, 5) different from np.arange(0, 1, 0.25)?

    linspace takes a count of points and includes the stop value by default, giving 0, 0.25, 0.5, 0.75, 1. arange excludes the stop value.
  3. 3. Why should you not print the result of np.empty((3, 3))?

    np.empty skips initialization for speed, so the values are whatever was in that memory. Write real values before reading.
  4. 4. What is np.repeat(np.array([1, 2]), 2)?

    repeat duplicates each element in place: 1, 1, 2, 2. tile would give 1, 2, 1, 2.

Summary

  • zeros, ones, full and empty build arrays of a shape; the *_like versions copy shape and dtype.
  • arange steps by a size, linspace gives a fixed count of points including the end, logspace spaces them logarithmically.
  • eye, identity and diag create identity and diagonal matrices or extract diagonals.
  • meshgrid and fromfunction generate coordinate grids and index-based tables.
  • tile repeats the whole array, repeat repeats each element.

Next: Data Types (dtype)