Search code examples
pythonpython-3.xvisual-studio-codedebuggingcompiler-errors

IndexError does not occur while debugging


I have some python code and every time I just run it (through Visual Studio Code), I get an IndexError at the end when I iterate through a list. However, when I try to debug the code to find out what went wrong, the code works just fine and I get the correct result, and exactly what I expect - and no error. I already tried to clear all caches, and even went so far as to change to a different computer to try it - just for it to occur on that other machine too.

To illustrate what I am doing, I have an array of integers, e.g. [0, 1, 0, 2, 1, 2, 2], where the integer denotes which Job an Operation belongs to, and the number of occurrence determines which operation of the job it is. E.g., the 0 at index 0 is Operation 0 of Job 0, while the 0 at index 2 is Operation 1 of Job 0.

    jobs = []
    for i in range(len(sequence)):
        if sequence[i] not in jobs:
            jobs.append(sequence[i])

    next_operations = [0] * len(jobs)

    for i in range(len(sequence)):
        job = sequence[i]
        operation = next_operations[job]
        next_operations[job] += 1

When I run the script the line operation = next_operations[job] is causing the Error IndexError: list index out of range.

As already mentioned, I tried debugging the code - but the issue does no longer occur. The error happens every time when I run the code normally, but never during debugging. I reset everything, restarted the computer to make sure there is no weird cache, changed to a different computer, even switched python versions (3.11, 3.10, 3.9) but all leads to the same result. I'm assuming (more like hoping) that there is some obvious config I messed up somehow, but I can not find anything so far. Anyone had a similar situation?


Solution

  • I actually figured out the answer to this one, though I'm still not sure what exactly caused it. After reinstalling everything (including Python), it worked again - I had multiple Python versions installed (required for different projects), and at some point a change I made to one of them must have messed up something they shared for the other one. Re-installing fixed the issue, the code was already correct as it was.