jeudi 11 avril 2019

Why do I get an 'IndexError: list index out of range' when I try to remove a record from my list in the except block

When I try running this function, I get an Index error: list out of range. The error occurs in the except block of the code when I try to use list.remove(list[i]). Not sure why I'm getting the out of range error, and any help would be much appreciated!

I've already tried debugging with various print statements around my function, and I saw that my record is fine, it just throws this error whenever I try to remove the record in my except block.

def subnet_insertion_sort(list):
    with open('bad_subnets.csv', 'w') as z:
        # Traverse through 1 to len(list)
        for i in range(1, len(list)):
            # extracts subnet from current list observed in list
            # and casts it as a ip_network objects
            try:
                key_subnet = ipaddress.ip_network(unicode(list[i][0]))

                j = i - 1
                # Move elements of list[0..i-1], that are
                # greater than key, to one position ahead
                # of their current position
                while (j >= 0 and key_subnet < ipaddress.ip_network(unicode(list[j][0]))):
                        temp = list[j]
                        list[j] = list[j + 1]
                        list[j + 1] = temp
                        j -= 1
            except:
                print("invalid subnet found: " + list[i][0] +  " on line " + str(i) + ". It has been added to bad_subnets.csv")
                writer_z = csv.writer(z)
                writer_z.writerow(list[i])
                list.remove(list[i])
                continue

        return list

My expected result would be that the function runs properly and I received a list without the invalid subnets, but my actual output is the Index error: list out of range.

Aucun commentaire:

Enregistrer un commentaire