Murtagh
Murtagh

Reputation: 23

List of lists not correctly assigining values Python

I have created a basic python program that is eventually going to try to be usable with Matricies, but I have come up against an issue that I can't understand.

When setting the 0'th element of the 0'th list, the program assignes the 0'th element of the first list to the same value (in this case one)

There is no reason for it to do so, as the program has no imported modules or anything else that should be affecting what I've already written

Please help

class Matrix(object):

    def createMatrix(self):     
        self.values = [1, 2, 3, 4]
        self.rows = 2
        self.coloms = 2

        self.colomList = [0] * self.coloms
        self.matrix = [self.colomList] * self.rows

test = Matrix()
test.createMatrix()

print(test.matrix)
test.matrix[0][1] = 1
print(test.matrix)

Upvotes: 1

Views: 66

Answers (1)

Phydeaux
Phydeaux

Reputation: 2855

You are creating a list, [0, 0], and then assigning that same list to both rows. Try this instead (note the correct spelling of "columns"):

def create_matrix(self):
    # self.values = [1, 2, 3, 4]
    self.rows = 2
    self.columns = 2

    self.matrix = [[0 for _ in range(self.columns)] for _ in range(self.rows)]

Just a suggestion, but you might also want to change the method to accept arguments for the width and height, and use the __init__ method to do all this when you instantiate the object:

class Matrix(object):
    def __init__(self, width=2, height=2):
        self.width = width
        self.height = height
        self._matrix = [[0 for _ in range(width)] for _ in range(height)]

print(Matrix()._matrix)      # uses default values: [[0, 0], [0, 0]]
print(Matrix(4, 3)._matrix)  # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

As a further improvement, we can see that the width and height depend on self._matrix, so we could compute those dynamically instead of storing them as attributes, to make sure they don't get out of sync:

class Matrix(object):
    def __init__(self, width=2, height=2):
        self._matrix = [[0 for _ in range(width)] for _ in range(height)]

    def height(self):
        return len(self._matrix)

    def width(self):
        return len(self._matrix[0])

print(Matrix(4, 3).width())   # 4
print(Matrix(4, 3).height())  # 3

Upvotes: 1

Related Questions