Fancy indexing lets you pick specific items from data using lists of positions. It helps you get or change many values at once easily.
Fancy indexing with integer arrays in NumPy
import numpy as np # Create an array array = np.array([10, 20, 30, 40, 50]) # Use a list or array of integers to pick elements indexes = [1, 3, 4] selected_elements = array[indexes]
The indexes can be a Python list or a NumPy array of integers.
Fancy indexing returns a new array with the selected elements.
import numpy as np array = np.array([5, 10, 15, 20, 25]) indexes = [0, 2, 4] print(array[indexes])
import numpy as np array = np.array([5, 10, 15, 20, 25]) indexes = [] print(array[indexes])
import numpy as np array = np.array([5]) indexes = [0] print(array[indexes])
import numpy as np array = np.array([5, 10, 15, 20, 25]) indexes = [4, 0] print(array[indexes])
This program shows how to pick elements from an array using a list of indexes, then change those elements in the original array.
import numpy as np # Create an array of numbers numbers = np.array([100, 200, 300, 400, 500]) print("Original array:", numbers) # Choose indexes to select selected_indexes = [1, 3, 4] # Use fancy indexing to get elements at these positions selected_numbers = numbers[selected_indexes] print("Selected elements at positions 1, 3, 4:", selected_numbers) # Change elements at these positions numbers[selected_indexes] = [210, 410, 510] print("Array after updating selected positions:", numbers)
Time complexity is O(k) where k is the number of indexes selected.
Space complexity is O(k) for the new array created by fancy indexing.
A common mistake is using indexes out of range, which causes an error.
Use fancy indexing when you want to select or update multiple specific elements at once. For continuous slices, normal slicing is simpler and faster.
Fancy indexing lets you pick or change many elements by giving their positions in a list.
It works with lists or arrays of integers as indexes.
It creates a new array of selected elements or updates the original array if assigned.