0

I have a problem with creating objects, where 2D array has variable length. I keep getting error

self.state[i] = listt[i]
IndexError: list assignment index out of range

If i try to create object with array with 2 rows and 3 columns, it works. If i try create an object with 3 rows and 3 columns it fails with the error.

class node:
    def __init__(self, m, n, listt=None):
        self.not_in_place = -1
        self.m = m
        self.n = n
        self.state = [[m],[n]]
        if listt is not None:
            for i in range(self.m):
              self.state[i] = listt[i] 

start = [[0,1,2],[3,4,5],[6,7,8]] 
node(3, 3, start) # doesn't work


start_2 = [[0,1,2],[3,4,5]] 
node(2, 3, start_2) # work

What am i doing wrong ?

1 Answer 1

1

In python you can't initialize an array with a given size, just by giving the size, and also you don't need to

To assign the given list to state, copy it by doing

if listt is not None:
    self.state = list(listt)

The reason it worked in the second case, is that you created a list with 2 sublist, so the 2 boxes are created, and it's okay when you iterate over them, and also why it failed when you try a length of 3

state = [[2], [3]]  # [[2], [3]], and not [[,,], [,,]]

If you want to initialize empty, in case listt is None, you can do

class node:
    def __init__(self, m, n, listt=None):
        self.not_in_place = -1
        self.m = m
        self.n = n
        self.state = [[]] * m
        if listt is not None:
            self.state = list(listt)

    def __str__(self):
        return str(self.state)

if __name__ == '__main__':
    start = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    n = node(3, 3, start)
    print(n)  # [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

    n = node(2, 3, None)
    print(n)  # [[], []]
Sign up to request clarification or add additional context in comments.

2 Comments

great thanks ! Now i have another problem. How can i get position/index [x][y] of a number for instance 0 in the array ? I need it's position so i can do stuff with the array.
@TomášRončák to read [0, 1, 2] do state[0], to read 0 do state[0][0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.