📅  最后修改于: 2023-12-03 15:34:02.189000             🧑  作者: Mango
Lists are one of the most commonly used data structures in Python. They are used to store multiple items in a single variable. In Python, a list can be created by enclosing a sequence of values, separated by commas, inside square brackets [].
To access an item in a list, we use its index. Indexing in Python starts at 0, which means the first item in a list has an index of 0, the second item has an index of 1, and so on.
To access an item in a list, we use the square bracket notation followed by the index of the item we want to access. For example,
my_list = ['apple', 'banana', 'cherry', 'orange']
print(my_list[1]) # Output: banana
In the above example, we created a list with four items and printed the second item (index 1) using its index.
In addition to positive indices, we can also use negative indices to access items in a list. Negative indices count from the end of a list, with -1 being the index of the last item in the list.
my_list = ['apple', 'banana', 'cherry', 'orange']
print(my_list[-1]) # Output: orange
In the above example, we printed the last item in the list (index -1) using negative indexing.
We can also access a range of items in a list using slicing. Slicing is done using the colon operator ":".
my_list = ['apple', 'banana', 'cherry', 'orange']
print(my_list[1:3]) # Output: ['banana', 'cherry']
In the above example, we printed a range of items from the second item (index 1) to the third item (index 3-1=2) of the list using slicing.
We can change the value of an item in a list using its index.
my_list = ['apple', 'banana', 'cherry', 'orange']
my_list[1] = 'kiwi'
print(my_list) # Output: ['apple', 'kiwi', 'cherry', 'orange']
In the above example, we changed the second item (index 1) of the list to 'kiwi' using its index.
We can add or remove items in a list using its index.
my_list = ['apple', 'banana', 'cherry', 'orange']
my_list.insert(1, 'kiwi')
print(my_list) # Output: ['apple', 'kiwi', 'banana', 'cherry', 'orange']
my_list.pop(2)
print(my_list) # Output: ['apple', 'kiwi', 'cherry', 'orange']
In the above example, we added an item ('kiwi') at a specific index (1) using the insert() method and removed an item at a specific index (2) using the pop() method.
In summary, Python list indexing is a powerful tool that allows us to access individual items, ranges of items, and modify items in a list. Understanding list indexing is essential for working with lists in Python.