suayip uzulmez suayip uzulmez - 1 year ago 45
Python Question

Python: list index out of range, but there are items in list?

I'm trying to add 18 list items to a 3 text file, 6 items for each them.

text files are correct but third one
only gets 3 items.

mainStudents = ["1 Name Surname D1", "2 Name Surname D2" ...16x]
def randomize(path):
count = 0
currentpathIs = getprojdir + "\\" + "\shuffled" + path
with open(currentpathIs, "a+") as file:
while True:
file.write(mainStudents[count] + "\n")
count += 1
except Exception as e:

if count == 6:


I'm getting this error:

Traceback (most recent call last):

File "C:\Users\user\Desktop\New folder\", line 53, in randomize(paths[2])

File "C:\Users\user\Desktop\New folder\", line 43, in randomize
file.write(mainStudents[count] + "\n")

IndexError: list index out of range

But there's 3 items left in

Answer Source

The problem you have is that when you delete the item from your list, you are then decreasing its size. Therefore, your count is going to increment and then try to access an index that no longer exists. Take a very simple example of just having a list of size two:

mainStudents = ["1 Name Surname D1", "2 Name Surname D2"]

Now, when you call your method, what is going to happen, the first iteration will work, because you will access mainStudents[0].

But, on your second iteration, you have deleted that item from the list, so now your list looks like:

['2 Name Surname D2']

Which is now a list of size one, and the index access for it would be 0.

So, the next iteration of your while loop will have count at 1. Therefore, that is exactly where your IndexError is coming from.

The combination of deciding to use a while loop and del items from your list is what is causing issues. Instead, choose what it is exactly you want to iterate over, which from your logic seems like it is mainStudents. So why not just do that instead?

def randomize(path):
    currentpathIs = getprojdir + "\\" + "\shuffled" + path
    with open(currentpathIs, "a+") as file:
        for student in mainStudents:
            file.write(student + "\n")

And you can further simplify that by simply taking your list and converting it to a string separated by \n by using the available string method, join:


So, your code can be further simplified to:

def randomize(path):
    currentpathIs = getprojdir + "\\" + "\shuffled" + path
    with open(currentpathIs, "a+") as file: