algoProg
algoProg

Reputation: 728

Python index error: How to debug

I have following code:

import csv
import sys

with open('zone1.txt', 'r') as z1:
    zone1 = z1.readlines()

with open('Derived_Dataset.csv', 'r') as ud:
    UMC_Data = ud.readlines()

no_rows = 0

for row1 in zone1:
    for row2 in UMC_Data:
        if row1.split(",")[2] == row2.split(",")[2] and row1.split(",")[3] == row2.split(",")[3]:
            print(row2)
            no_rows = no_rows = 1

print('\n')
print(no_rows)

I get the indexerror as follows:

    Traceback (most recent call last):
  File "C:/Users/gakadam/PycharmProjects/waferZoning/main.py", line 14, in <module>
    if row1.split(",")[2] == row2.split(",")[2] and row1.split(",")[3] == row2.split(",")[3]:
IndexError: list index out of range

As both files are quite big, usual debug options (JetBrains) are not feasible to use. Is there a debugger which can efficiently help me to narrow down which of the variable(s) goes out of its limits? Thank you.

Upvotes: 2

Views: 650

Answers (1)

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

rewrite your for loop as follow :

for iIdx1, row1 in enumerate(zone1):
    lsSplitted = row1.split(",")
    assert(len(lsSplitted) >= 4), "Error in row1 line no {} line {}".format(iIdx1, str(row1))
    for iIdx2, row2 in enumerate(UMC_Data):
        lsRow2Splitted row2.split(",")
        assert(len(lsRow2Splitted) >= 4), "Error in row2 line no {} line {}".format(iIdx2, str(row2))
        if (lsSplitted[2] == lsRow2Splitted[2] and 
            lsSplitted[3] == lsRow2Splitted[3]):
            print(row2)
            no_rows = no_rows = 1

I think the assertions will help you figure out the lines where index error is coming up.

Upvotes: 1

Related Questions