How to use indexing in Python?
In Python, you can use indexes to access elements in containers such as lists, tuples, and strings. Indexes are integers starting from 0 and represent the position of the element in the container.
For example, for a list:
my_list = [1, 2, 3, 4, 5]
We can access elements in a list using indexes. For example, to access the first element in a list, we can use index 0:
print(my_list[0]) # 输出:1
To access the third element in the list, you can use the index 2:
print(my_list[2]) # 输出:3
To access the last element in the list, you can use a negative index of -1.
print(my_list[-1]) # 输出:5
One can also access characters within a string using indexing. For example:
my_string = "Hello, World!"
print(my_string[0]) # 输出:H
print(my_string[-1]) # 输出:!
For tuples, the way to use indexes is the same as with lists. For example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[2]) # 输出:3