Search code examples
pythonlistmultidimensional-arrayoutofrangeexception

python list of lists index out of range


I have read in a matrix of numbers and I am trying to work with each cell and perform tests on each one. If the number is != 0 I want to use it so if it is 0 I am currently incrementing x and y to find a non zero number.

In the end I will just be first looking across the top row and then if they are all 0 start looking down the first column and this works fine as long as I am referring to just one (row or column).

Why am I receiving this error? Am I thinking incorrectly about how the cells are set up or is my code wrong?

The matrix looks like this:

0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,0,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0

When I start trying to do this:

y = y + 5
x = x + 5
node = Alist[x][y]

I receieve an error saying:

node = Alist[x][y]
IndexError: list index out of range

If I was to just write:

y = y + 5
node = Alist[x][y]
print node

It would work completely fine but when I introduce both x and y I start to get list index out of range problems. In my mind it should now read:

node = Alist[5][5] 

Which is 0 if you follow the matrix

def create_matrix(file):
    with open('network.txt') as f:
        Alist = []
        for line in f:
            part = []
            for x in line.split(','):
                part.append(int(x))
            Alist.append(part)
    return Alist

#used to set the start node, used once          
def start_node(Alist):
        x=0
        y=0
        #point node to pos [0][0] of Alist
        node = Alist[x][y]
        #test if node == 0
        while node == 0:
                y = y + 5
                x = x + 5
                node = Alist[x][y]
        #create a list to hold co-ordinates
        if node != 0:
                #return node for processing by check_neighbours
                return node, x, y

#def current_node(Alist, x, y)

#test neighbours to see if they can be used
def check_neighbours(node, Alist, i, j):
        #print out values of x and y
        print "x = %d" %i
        print "y = %d" % j
        print "node in check_neighbours is " + str(node)


#running of code begins here
def main():
        file = ("F:/media/KINGSTON/Networking/network.txt")
        Alist = create_matrix(file)
        node, x, y = start_node(Alist)
        check_neighbours(node, Alist, x, y)
main()

Solution

  • It's the second iteration round the loop that's failing, because it sets x and y to 10, where you only have 7 items in each dimension.

    Your loop while node == 0: moves down the diagonal of the matrix five steps at a time, falling off the end. It would fall off the end even if it went one at a time, because that diagonal is all zeros.

    Perhaps you meant if node == 0?

    I don't know what the code is actually trying to do, but you need to rethink the algorithm. :-)