Indexing
Indexing is the process of accessing individual elements within a sequence, such as a string, list, or tuple, using their position or index number.
How Indexing Works
· Python uses zero-based indexing, meaning the first element has an index of 0, the second has an index of 1, and so on.
·
You access elements using square brackets []
with the index inside.
Example with a List
Python
my_list = [
10,
20,
30,
40]
first_element = my_list[
0]
# Accesses the first element (10)
third_element = my_list[
2]
# Accesses the third element (30)
Example with a String
Python
my_string =
"Python"
first_character = my_string[
0]
# Accesses the first character ('P')
last_character = my_string[-
1]
# Accesses the last character ('n')
Negative Indexing
You can use negative indices to access elements from the end of a sequence:
Python
my_list = [
10,
20,
30,
40]
last_element = my_list[-
1]
# Accesses the last element (40)
Slicing
Indexing can also be used for slicing, which extracts a portion of a sequence:
Python
my_list = [
10,
20,
30,
40,
50]
sublist = my_list[
1:
4]
# Extracts elements from index 1 to 3 (exclusive)
Key Points
· Indexing starts from 0.
· Negative indices access elements from the end.
· Slicing creates a new sequence.
· Be careful with index out of range errors.
By understanding indexing, you can effectively manipulate and access elements within sequences in Python.