How to Indexing and slicing in Python
Published on Aug. 22, 2023, 12:16 p.m.
Indexing and slicing are common operations used to access and modify elements in Python sequences like lists, strings, and tuples.
Indexing in Python is used to obtain individual elements of a sequence by their position (index) within the sequence. The index of the first element is 0, the index of the second element is 1, and so on. To access an element in a sequence using indexing, you use square brackets []
with the index inside, like this:
my_list = [10, 20, 30, 40, 50]
first_element = my_list[0] # 10
second_element = my_list[1] # 20
Slicing in Python is used to extract a sub-sequence (slice) of elements from a sequence. Slicing is done using the colon operator :
inside the square brackets []
. The expression a[m:n]
returns the sub-sequence of a
starting at index m
and ending just before index n
. The slice operator a[m:n:k]
returns every k
-th element from the start index m
up to but not including the end index n
. Here’s an example:
my_list = [10, 20, 30, 40, 50]
first_three_elements = my_list[0:3] # [10, 20, 30]
every_other_element = my_list[::2] # [10, 30, 50]
Note that slicing can also be used with negative indexing, where -1 refers to the last element, -2 refers to the second-to-last element, and so on.
These concepts can also be applied to other sequence types like strings and tuples.