IndexError: list index out of range
In Python, lists which are mutable that means the size is not fixed. So, you can add items to these lists after that have been already declared and you can access its elements by its index . You can add as many items as you want, but now the question arises; what happens if you try to access the item which is not in the list ?
This error basically means you are trying to access a value at a List index which is out of bounds i.e greater than the last index of the list or less than the least index in the list. So the first element is 0, second is 1, so on. So if there are n elements in a list, the last element is n-1 . If you try to access the empty or None element by pointing available index of the list, then you will get the "List index out of range " error. To solve this error, you should make sure that you're not trying to access a non-existent item in a list.
Python IndexError problem has to do with a very common beginner problem when access List elements by its index.
Here you can see, the IndexError is raised when attempting to retrieve an index from a sequence, and the index isn't found in the sequence.
Length of list is 3, so if you access elements in list whose index greater than 2 then it will show an error:
Here index is 3 which is equal to length of list so you can't access it. If you have a list with 3 items, the last one is MyList because the way Python indexing works is that it starts at 0.
An index in Python refers to a position within an ordered list . To retrieve an element of the list, you use the index operator () . Using indexing you can easily get any element by its position. Python strings can be thought of as lists of characters ; each character is given an index from zero (at the beginning) to the length minus one (at the end).
Lists are "zero indexed" , so MyList returns the left-most (i.e. zero-th) item in the list, and MyList returns the second item (i.e. one item to the right of the zero-th item). Since there are 3 elements in your list (MyList through MyList), attempting to access MyList throws an IndexError: list index out of range , since it is actually trying to get the fourth element, and there isn't one.
You can access the List elements at the end by adding a minus also.