Indexing and slicing are fundamental concepts used to retrieve and modify data within sequences like strings, lists, and arrays. Python uses zero-based indexing, meaning that the first element of any sequence is accessed with index 0, not 1. Indexing allows you to access individual elements, while slicing lets you access a subset, or a slice, of a sequence.
Note
0-based indexing offers some practical advantages in terms of memory management and algorithmic efficiency. This indexing system simplifies pointer arithmetic, as the index corresponds directly to the offset from the base address in memory. With 1-based indexing, an extra subtraction is needed. There is also a historical reason due to the influence of earlier programming languages, like C, that were also 0-based indexing.
Syntax for indexing and slicing one-dimensional arrays
# Indexing a one-dimensional arrayelement = array[index]# Slicing a one-dimensional arraysub_array = array[start_index:end_index:step]
Omitting start_index (e.g., array[:end_index]) slices from the beginning to end_index.
Omitting end_index (e.g., array[start_index:]) slices from start_index to the end of the array.
# Generate intengers from 0 to the specified number (non-inclusive)numbers =list(range(10)) print(numbers)# Find the first element of the list (indexing operation)print(numbers[0])# First and second elementprint(numbers[0:2]) # Print last three elementsprint(numbers[-3:]) # All elements (from 0 and on)print(numbers[0:])# Every other element (specifying the total number of element)print(numbers[0:10:2]) # Every other element (without specifying the total number of elements)print(numbers[0:-1:2])# Print the first 3 elementsprint(numbers[:3])# Slice from the 4th to the next-to-last elementprint(numbers[4:-1]) # Print the last item of the listprint(numbers[-1])print(numbers[len(numbers)-1])
Syntax for indexing and slicing two-dimensional arrays
# Indexing a two-dimensional arrayelement = array[row_index][column_index]# Slicing a two-dimensional array (with step)sub_array = array[row_start:row_end:row_step, column_start:column_end:column_step]
Omitting row_start (e.g., array[:row_end, :]) slices from the beginning to row_end in all columns. Here “all columns” is represented by the : operator. Similarly you can use : to represent all rows.
Omitting row_end (e.g., array[row_start:, :]) slices from row_start to the end in all columns.
import numpy as np# Indexing and slicing a two-dimensional arraynp.random.seed(0)M = np.random.randint(0,10,[5,5])print(M)# Write five python commands to obtain:# top row# bottom row# right-most column# left-most column# upper-right 3x3 matrix