Casper
Casper

Reputation: 189

List/matrix is not saving the correct values

I have a weird problem with an assignment I got. We are supposed to implement a matrix class. Well, it's not that hard, but Python just won't do as I tell it to. But I'm sure there is an explanation.

The problem is that, in the following code, I try to save values (provided in a list) into a matrix.

class simplematrix:
    matrix = [[]]
    def __init__(self, * args):
       lm = args[0]
       ln = args[1]
       values = args[2]
       self.matrix = [[0]*ln]*lm

       for m in range(lm):
           for n in range(ln):
               self.matrix[m][n] = values[(m*ln)+n]

vals = [0,1,2,3,4,5]
a = simplematrix(2,3,vals)

When I try to print the matrix, I expect to get [[0,1,2],[3,4,5]], which I get if I run it by hand, on a piece of paper. If I print the matrix from Python I get [[3,4,5],[3,4,5]] instead. Can anyone tell me why Python acts like this, or if I made some stupid mistake somewhere? :)

Upvotes: 2

Views: 159

Answers (3)

TartanLlama
TartanLlama

Reputation: 65600

The answers by Tim and aix correct your mistake, but that step isn't even necessary, you can do the whole thing in one line using a list comprehension:

self.matrix = [[values[m*ln+n] for n in range(ln)] for m in range(lm)]

You can also say:

vals = range(6)

as opposed to what you already have. This tidies up your code and makes it more Pythonic.

Upvotes: 2

NPE
NPE

Reputation: 500267

The problem is in [[0]*ln]*lm. The result consists of lm references to the same list, so when you modify one row, all rows appear to change.

Try:

self.matrix = [[0]*ln for i in xrange(lm)]

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

The problem is that self.matrix = [[0]*ln]*lm doesn't give you a list of lm separate sublists, but a list of lm references to the single same list [[0]*ln].

Try

self.matrix = [[0]*ln for i in range(lm)]

(If you're on Python 2, use xrange(lm) instead).

Upvotes: 1

Related Questions