python list index out of range
时间: 2023-10-12 10:11:47 浏览: 87
This error occurs when you try to access an index in a list that does not exist. For example, if you have a list of 5 elements and you try to access the 6th element using its index, you will receive this error.
Here is a sample code that will raise this error:
```
my_list = [1, 2, 3, 4, 5]
print(my_list[6]) # This will raise an IndexError because the list has only 5 elements
```
To avoid this error, make sure that you are not trying to access an index that is out of range. You can use the `len()` function to get the length of the list and then use that value to access elements in the list.
```
my_list = [1, 2, 3, 4, 5]
if len(my_list) > 6:
print(my_list[6])
else:
print("Index out of range")
```
In the above code, we check if the length of the list is greater than 6 before accessing the 6th element. If the length is less than 6, we print a message indicating that the index is out of range.
阅读全文