Python Indexing
tags: #python/intro
What is indexing?
In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number[1].
Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on. Note that index positions are named from right to left.
If the iterable object,s, has n items, the last item is s[n-1].
Python has the following built-in sequence types such as: lists, strings, tuples.
We can index through a sequence by specifying the index number of the desired item in an iterable object (sequence) using the index operator ( [] ) to enclose the index number.
The index number must be an integer and starts at zero; therefore, the nth character is at index n-1.
Positive Indexing vs Negative Indexing
There are two indexing system in Python:
-
Positive Indexing: i.e.
0 indexing, where the first element starts with 0 -
Negative Indexing: where we count backwards, such that first element at the end of list starts with
. This is useful in selecting elements at the end of the list.

IndexErrorAn IndexError can occur when we use an index number that is outside the range of the sequeence.
Example of indexing a Python List:

Python Slicing
Python slicing is used to return a segment of a sequence or iterable object. This allows you to create a new sequence that consists a subset of the original elements.
Note that a slice will always return a list object.
Basic Syntax
sequence[start:stop:step]
start: The index of the first element to include in the slice. It is inclusive, meaning the element at this index is part of the slice.stop: The index of the first element that is not included in the slice. It is exclusive, meaning the element at this index is not part of the slice.step(optional): The step or stride between elements. It specifies how many indices to skip. The default is 1.
stop value is beyond the length of the iterable object?No traceback. If the second number is beyond the end of the sequence/iterable object, it stops at the end. Code will execute up to the last item in the iterable object.
Examples:
# Slicing a List
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[2:7] # Get elements from index 2 to 6 (exclusive)
print(subset) # Output: [2, 3, 4, 5, 6]
# Slicing a String
my_string = "Hello, World!"
substring = my_string[7:12] # Get characters from index 7 to 11 (exclusive)
print(substring) # Output: World
# Slicing with a Step
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[1:9:2] # Get elements from index 1 to 8 (exclusive) with a step of 2
print(subset) # Output: [1, 3, 5, 7]e
Other Slicing Methods
Selecting all elements in a list
a[:]
Selecting the first n elements
a[:n]
Selecting the last n elements
a[-n:]
When you want to select all elements after the slide including the last
a[n:]