I created a class Matrix. I've been trying to fill this matrix by randomize method, But this error was shown:
self.data[i].append(value) IndexError: list index out of range
full code:
import random class Matrix: def __init__(self, rows, cols): self.rows=rows self.cols=cols self.data=[] def randomize(self): for i in range(self.rows): for j in range(self.cols): value=random.randint(0, 10) self.data[i].append(value)
You need to initialize the self.data list before accessing it with self.data[i] in the randomize function. You can do this with:
self.data=[[] for x in range(rows)]
1.4m articles
1.4m replys
5 comments
57.0k users