Skip to content
Home » numpy Part 5 – Indexing numpy Arrays

numpy Part 5 – Indexing numpy Arrays

Spread the love

Today we’ll be talking about indexing numpy arrays. I’m sure you know how to index regular Python sequences like strings, lists or tuples, just to mention a few. Just a quick reminder: you put the index you need inside a pair of square brackets. This is how you can retrieve an element from a sequence, as well as assign a new value to it.

Indexing 1-Dimensional numpy Arrays

Indexing a 1-dimensional array is pretty straightforward. It works just like with regular Python sequences. We also use square brackets. Let’s compare.

Here’s how you index a regular Python list:

>>> lst = [10, 20, 30, 40, 50]
>>> lst[0], lst[1], lst[-1]
(10, 20, 50)

By the way, if you’re wondering how negative indices work, they are just the indices from the end of a sequence to the beginning, so the last item is at index -1, the second item from the end is at index -2, and so on. This means each element of a sequence may be indexed in two equivalent ways: either with a positive index or with a negatice index. It depends on which one is more comfortable to use in any particular case.

And here’s how you index a numpy array:

>>> arr = np.array(lst)
>>> print(arr)
[10 20 30 40 50]
>>> arr[0], arr[1], arr[-1]
(10, 20, 50)

Multidimensional Arrays

With multidimensional arrays we can use the same syntax as with nested lists.

indexing numpy arrays

Here’s how you index a nested Python list:

>>> lst = [[11, 22, 33, 44], [18, 28, 38, 48]]
>>> lst[1][2]
38

So, we use the first index to retrieve the second sublist in the outer list, and then we use the second index to retrieve the third element in that sublist.

And here’s how you index a multidimensional numpy array:

>>> arr = np.array(lst)
>>> print(arr)
[[11 22 33 44]
 [18 28 38 48]]
>>> arr[1][2]
38

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

This works, but it’s inefficient because it creates a temporary intermediate array (arr[1] in this case) which is then indexed with the second index (2 in our case).

This is why it’s recommended to use a different way of indexing multidimensional arrays. We put all the indices in one pair of square brackets:

>>> arr[1, 2]
38

You can index your array to assign new values to its elements as well:

>>> arr[1, 2] = 50
>>> print(arr)
[[11 22 33 44]
 [18 28 50 48]]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply