Chase
Chase

Reputation: 287

2d list / matrix in python

I am trying to create a 4x4 matrix class in python...

I had the matrix being created like this -

class matrix:
    self.matrix = [[0 for x in range(4)] for y in range(4)]

i have tried to access the indices in this matrix like this for example -

myMatrix = matrix()
print(myMatrix.matrix[0][0])

however I get an error saying

AttributeError: myMatrix instance has no attribute '__getItem__'

I have tried adding a method to my matrix class like this-

def getValue(self, x, y):
    return self.matrix[x][y]

but I get an error saying TypeError: list indices must be integers

even when I tried self.matrix[0][0] it said they must be integers, any idea on how I can get simple 2d list/ matrix functionality in python?

I just want to be able to create a 4x4 2d list / matrix and access and change elements within it?

Upvotes: 0

Views: 611

Answers (2)

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8069

Initialize the matrix in __init__ method and define how to get element by index in __getitem__.

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]

    def __getitem__(self, item):
        return self.matrix[item]

m = matrix()
print(m[0][0]) # 0

But, as mentioned before, you can use numpy and other appropriate packages unless you need to implement some special extra-functionality for the matrix.

Upvotes: 0

Djaouad
Djaouad

Reputation: 22794

Yuo should initialize the matrix first, using an __init__ method:

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]

myMatrix = matrix()
print(myMatrix.matrix[0][0]) # => 0

And now you can create your getValue, which is better for later use:

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]
    def getValue(self, x, y):
        return self.matrix[x][y]

myMatrix = matrix()
print(myMatrix.matrix[0][0]) # => 0
print(myMatrix.getValue(0, 0)) # => 0

Upvotes: 1

Related Questions