This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Array operations

Indexing arrays

face Josiah Wang

Now, let’s talk about how to access elements in a np.array.

For a 1D array, you access elements just like a Python list. Slicing works too.

>>> x = np.array([1, 2, 3, 4, 5])
>>> print(x[0])
1
>>> print(x[-1])
5
>>> print(x[2:4])
[3 4]
>>> print(x[:3])
[1 2 3]

For multidimensional np.arrays, you can access indices at different axes/dimensions by separating the indices with a comma. Slicing will also work.

>>> y = np.array([[1, 2, 3, 5], [-1, 4, 7, 9]]) 
>>> print(y)
[[ 1  2  3  5]
 [-1  4  7  9]]
>>> print(y[0, 1])  # (row 0, col 1)
2 
>>> print(y[-1, -2]) # (last row, second-to-last col)
7  
>>> print(y[0:2, 2:4]) # slicing out a subset of the array
[[3 5]
 [7 9]]
>>> print(y[1:3, :-1]) # Try figuring this out yourself! It is a bit confusing!
[[-1  4  7]]
>>> print(y[:, :]) # What does this do?
????
>>> print(y[0]) # And this one?
????

While you can also use y[0][1] as in a Python list, this is much slower than y[0,1]. So use y[0,1] if you want your code to be more efficient!

Here’s an interesting thing you can do with np.array that you cannot do with Python lists. What do you think the following output will be? Test it out to see whether you are correct!

>>> y = np.array([[1, 2, 3, 5], [-1, 4, 7, 9]]) 
>>> print(y)
[[ 1  2  3  5]
 [-1  4  7  9]]
>>> print(y[[1, 0, 1], [3, 2, 0]])
???

You should think of the above a bit like zip(): selecting y[1, 3], y[0, 2] and y[1, 0] from the np.array. The result is [9 3 -1].