Share on:

#### Python NumPy For Your Grandma | Section 2.3 | Indexing And Modifying 1D Arrays

##### December 29, 2019
python courses

This video covers how to index and modify elements of a 1D NumPy array.

# Code

import numpy as np

# Suppose we have the following 1d array with 5 elements
foo = np.array([10, 20, 30, 40, 50])

# access the ith element of foo using foo[i-1], just like a python list
foo[0]  # 10, 1st element
foo[1]  # 20, 2nd element

# modify  ith value
foo[1] = -20  # [ 10, -20,  30,  40,  50]

# access the last element in the array
foo[4]  # 50

# access the last element in the array v2
foo[len(foo) - 1]  # 50

# access the last element in the array v3 using negative indexing
foo[-1]  # returns the last element in the array
foo[-2]  # returns the 2nd to last element in the array

# out of bounds error
foo[999]  # error

# access multiple elements at once
foo[[0, 1, 4]]  # [ 10, -20,  50]
foo[[0,1,0,1,0,1,0,1]]  # [ 10, -20,  10, -20,  10, -20,  10, -20]
foo[np.zeros(3, dtype = 'int64')]  # [10, 10, 10]

# use slicing, just like with python lists
# Slicing: foo[start index : end index : jump by]
foo[:2]  # [ 10, -20], get every element before index 2
foo[2:]  # [30, 40, 50], get every element from index 2 onward
foo[::2] # [10, 30, 50], get every other 2nd element

# modify multiple elements
foo[[0, 1, 4]] = [100, 200, 400]  # [100, 200,  30,  40, 400]

# Transcript

In this section, we’ll look at how to index a 1D array to access and modify its elements. We’ll start by making a 1d array called “foo” with 5 elements.
We can access the ith element just like a python list using square bracket notation where the first element starts at index 0.
We can modify the ith element just as easily.
Since we know foo has 5 elements, we can use index 4 to access the last element.
If we want to make that more dynamic, we can replace the index as the length of foo minus one.
But we can make that even simpler using negative indexing. Just like python lists, negative one returns the last element in the array, negative two returns the second to last element, and so on.
If we try to access an element outside the bounds of the array, we’ll get an “out of bounds” error.

If we want to access multiple elements at once, we can use a list or numpy array of indices. As always, our indices must be integers.
We can also use index slicing just like python lists.

• Foo colon two returns every element before the 2nd index.
• Foo two colon returns every element from index two onward.
• And foo colon colon two returns every 2nd element.

And of course, we can modify multiple elements at once if our list of values is the same size as our array subset.