Home > Mobile >  How do I solve the error, "IndexError: list index out of range"
How do I solve the error, "IndexError: list index out of range"

Time:05-18

This is my code I'm using, its suppose to get a line from the text file and separate it and get the key at the end and use that to get all the lines in order from least to greatest and make a paragraph, I cant find out how to fix the error IndexError: list index out of range "if book_list2 in book_dict:", can someone help me?1

The book_data.txt file looks like this and I need to sort it, as stated above

CodePudding user response:

It means book_list does not have have 3 elements. So book_list[2] is raising the error that you are trying to access an element that does not exist. Index in python start from 0, so a 2 element list will have final element at book_list[1].

If you are accessing the last element, you can also do book_list[-1]. This always gives the last element.

CodePudding user response:

An IndexError means that your code is trying to access an index that is invalid.

Let me explain it to you this way: You have a list of 5 elements: [‘a’,’b’,’c’,’d’,’e’] Now the max length is 5, so the indexes you can use to access the array are 0,1,2,3,4.

But if you try to access my_list[8] this would return you an error stating an index error that points to the invalid index to get an item from a list that doesn’t exist.

Trying to understand your case, you can do the following, you need to make sure that the variable book_list has atleast 2 elements within it to access the second element.

In simple words, you can’t take out 2 apples from a box that contains only 1 or no apples.

CodePudding user response:

@Trishant Pahwa Explain it very well, this error means that you are trying to get an item that doesn't exist. let say

book_list = ['book_01', 'book_02', 'book_03']

In this case, book_list is a list of length 3 (three items) but since the list uses an index you will have 0, 1, and 2 indexes.

if you want to get book_01 you will use book_list[0] because the item is in the index 0. Now if you try to do book_list[3] you will get the error IndexError because there is nothing in index 3.

we will need to know what is in book_data.txt to know what are you getting in the line 9 book_list = book_line.strip().split("|")

  • Related