How to use indexing in Python?

In Python, you can access elements in data types such as strings, lists, and tuples using indexes. Indexes start from 0, representing the first element, and increase sequentially.

For example, for the string “Hello World”, you can use indexes to access each character.

str = "Hello World"
print(str[0])  # 输出第一个字符 "H"
print(str[1])  # 输出第二个字符 "e"

You can also access each element in a list using an index.

list = [1, 2, 3, 4, 5]
print(list[0])  # 输出第一个元素 1
print(list[2])  # 输出第三个元素 3

To access the last element, you can use a negative index, for example:

print(list[-1])  # 输出最后一个元素 5
print(list[-2])  # 输出倒数第二个元素 4

The usage of tuples and strings is similar to that of lists.

bannerAds