Numpy Arrays: Exercises


3. Slicing NumPy Arrays. In Python, you can extract a portion of a NumPy array using slicing. Slicing is done by specifying a start and end index, separated by a colon :.

For example, numbers[1:4] returns a new NumPy array with items from the second to the fourth (excluding the fourth) item in the original array.


# Import the NumPy library import numpy as np # Create a NumPy array of numbers numbers = np.array([1, 2, 3, 4, 5]) # Slice the array to extract the second to fourth numbers selected_numbers = ___ # Print the selected numbers print(selected_numbers) # Import the NumPy library import numpy as np # Create a NumPy array of numbers numbers = np.array([1, 2, 3, 4, 5]) # Slice the array to extract the second to fourth numbers selected_numbers = numbers[1:4] # Print the selected numbers print(selected_numbers) test_object("selected_numbers") success_msg("You have correctly sliced the NumPy array to select specific numbers.")
To slice a NumPy array, use the format start_index:end_index to extract a portion of the array.

Previous Exercise Next Exercise