List index out of range là gì

I am a beginner programmer and im not sure what this means...

Index Error: list index out of range

2

If you are working with lists in Python, you have to know the index of the list elements. This will help you access them and perform operations on them such as printing them or looping through the elements. But in case you mention an index in your code that is outside the range of the list, you will encounter an IndexError.

List index out of range” error occurs in Python when we try to access an undefined element from the list.

The only way to avoid this error is to mention the indexes of list elements properly.

Example: 

# Declaring list list_fruits = ['apple', 'banana', 'orange'] # Print value of list at index 3 print[list_fruits[3]];

Output:

Traceback [most recent call last]:   File "list-index.py", line 2, in     print[list_fruits[3]]; IndexError: list index out of range

In the above example, we have created a list named “list_fruits” with three values apple, banana, and orange. Here we are trying to print the value at the index [3].

And we know that the index of a list starts from 0 that’s why in the list, the last index is 2, not 3

Due to which if we try to print the value at index [3] it will give an error.

Correct Example: 

# Declaring list list_fruits = ['Apple', 'Banana', 'Orange'] # Print list element at index 2 print[list_fruits[2]];

Output: 

Orange # Declaring list list_fruits = ['Apple', 'Banana', 'Orange'] i=0 # while loop less then and equal to list "list_fruits" length. while i

Chủ Đề