2

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? :)

3 Answers 3

2

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)]
2
  • Ah okay. Thanks a lot for the fast answer and the explanation. I don't see the use of making references to the same list multiple times, so I would never have figured it out myself :) Once again - thank you.
    – Casper
    Dec 13, 2010 at 12:34
  • 1
    You're very welcome. Everyone gets caught out by this at some point.
    – NPE
    Dec 13, 2010 at 12:38
2

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.

2
  • Wow, that's compact, but much nicer. Thanks for the tip.
    – Casper
    Dec 13, 2010 at 12:36
  • No problem, that's the beauty of Python for you. Dec 13, 2010 at 12:43
1

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).

2
  • Whats the difference between xrange and range?
    – Casper
    Dec 13, 2010 at 12:35
  • xrange essentially only stores the list elements when it needs to, so if you are using data with large list structures, a lot less memory is used up. It's actually a bit more complicated in that xrange returns an xrange object rather than a list, but as far as you need to know, it's for reducing memory use. Dec 13, 2010 at 12:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.