NumPy Creating Arrays

Lesson 3 of 17

You can create a NumPy array from a Python list or tuple with np.array(), or let NumPy build one for you with functions such as zeros(), arange() and linspace().

Create an array from a list or tuple

Example

Python
import numpy as np

from_list = np.array([10, 20, 30])
from_tuple = np.array((1.5, 2.5, 3.5))

print(from_list)
print(from_tuple)

Output

Plain Text
[10 20 30]
[1.5 2.5 3.5]

Dimensions in arrays

A dimension is one level of nesting. The ndim attribute tells you how many dimensions an array has.

  • 0-D — a single value (a scalar)

  • 1-D — a row of values, like a list

  • 2-D — rows and columns, like a table or a matrix

  • 3-D — a stack of 2-D tables

Example

Python
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(a.ndim, b.ndim, c.ndim, d.ndim)
print(c)

Output

Plain Text
0 1 2 3
[[1 2 3]
 [4 5 6]]

Arrays filled with zeros, ones or any value

Example

Python
import numpy as np

print(np.zeros(3))
print(np.ones((2, 3)))
print(np.full((2, 2), 7))

Output

Plain Text
[0. 0. 0.]
[[1. 1. 1.]
 [1. 1. 1.]]
[[7 7]
 [7 7]]

Pass one number for a 1-D array, or a tuple such as (2, 3) for 2 rows and 3 columns. zeros() and ones() create floats by default.

Ranges of numbers: arange() and linspace()

np.arange(start, stop, step) works like Python's range() — the stop value is not included. np.linspace(start, stop, num) returns num evenly spaced values and does include the stop value.

Example

Python
import numpy as np

print(np.arange(0, 10, 2))
print(np.linspace(0, 1, 5))

Output

Plain Text
[0 2 4 6 8]
[0.   0.25 0.5  0.75 1.  ]

The identity matrix

Example

Python
import numpy as np

print(np.eye(3))

Output

Plain Text
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

np.eye(n) creates an n × n matrix with ones on the diagonal and zeros everywhere else. You will meet it again in the linear algebra lesson.