NumPy Tutorial menu

NumPy Creating Arrays

There are many ways to create a NumPy array, from a list or with built-in helper functions.

From a List or Tuple

Pass a list (or tuple) to np.array():

Example

python
import numpy as np

a = np.array([10, 20, 30])
b = np.array((1.5, 2.5, 3.5))
print(a)
print(b)
Output
[10 20 30]
[1.5 2.5 3.5]

Dimensions

The number of dimensions tells you how many "levels" of nesting an array has.

DimensionsLooks likeExample
0-DA single numbernp.array(42)
1-DA row of numbersdaily temperatures of one week
2-DA table with rows and columnsmarks of students in subjects
3-DSeveral tables stackedmarks of students, per subject, per term

Example

python
import numpy as np

zero_d = np.array(42)
one_d = np.array([1, 2, 3])
two_d = np.array([[1, 2, 3], [4, 5, 6]])
three_d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(zero_d.ndim, one_d.ndim, two_d.ndim, three_d.ndim)
print(two_d)
Output
0 1 2 3
[[1 2 3]
 [4 5 6]]

The ndim attribute gives the number of dimensions.

Every row of a 2-D array must have the same length. np.array([[1, 2], [3]]) raises an error, because NumPy needs a proper rectangle.

A 2-D Example: Marks Table

Example

python
import numpy as np

# rows = students, columns = Maths, English, Science
marks = np.array([
    [85, 72, 90],
    [60, 88, 75],
    [92, 95, 89]
])
print(marks)
print("Shape:", marks.shape)
Output
[[85 72 90]
 [60 88 75]
 [92 95 89]]
Shape: (3, 3)

Helper Functions

You often need an array before you have the data. NumPy has functions for that:

Example

python
import numpy as np

print(np.zeros(4))
print(np.ones((2, 3)))
print(np.full(3, 7))
print(np.eye(3))
Output
[0. 0. 0. 0.]
[[1. 1. 1.]
 [1. 1. 1.]]
[7 7 7]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Ranges of Numbers

np.arange() works like Python's range(), but returns an array. np.linspace() gives a fixed count of evenly spaced numbers between two values.

Example

python
import numpy as np

print(np.arange(5))
print(np.arange(2, 20, 4))
print(np.linspace(0, 1, 5))
print(np.linspace(0, 100, 3))
Output
[0 1 2 3 4]
[ 2  6 10 14 18]
[0.   0.25 0.5  0.75 1.  ]
[  0.  50. 100.]
FunctionWhat it makes
np.array(list)Array from your data
np.zeros(shape)All zeros
np.ones(shape)All ones
np.full(shape, value)All the same value
np.eye(n)Identity matrix (1s on the diagonal)
np.arange(start, stop, step)Numbers with a fixed step
np.linspace(start, stop, num)A fixed number of evenly spaced values

arange does not include the stop value, but linspace does include it by default.

Exercise

Exercise

What is the ndim of np.array([[1, 2], [3, 4], [5, 6]])?

Learn NumPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp