On Wed, Jun 10, 2009 at 04:57:39PM +0530, Aman Aggarwal wrote: > > I am reading "How to think like a computer scientist" which is an > introductory test in Python. > > I wanna clarify the behaviour of multiply operator(*) when applied to > list(data structure). > > > I wonder why > > [[0] * columns] * rows > > causes "...each row is an alias of the other rows..." > > but not > > [[0] * columns] > > i.e. why each [0] in a row is not an alias of other row element.
It is bit tricky in that code.. You have to understand that in the second option, the matrix is formed row-by-row, wherein a new row (list) is created as [0] * columns. This is what the second version essentially is doing: >>> rows = 2 >>> cols = 2 >>> mat = [] >>> mat = [[0] * cols] # first row >>> mat = mat + [[0] * cols] # second row >>> mat [[0, 0], [0, 0]] >>> mat[0][0] = 'Spam' >>> mat [['Spam', 0], [0, 0]] >>> This is the what the first version of the code was doing. >>> rows = 2 >>> cols = 2 >>> mat = [] >>> mat = [[0] * cols] # first row >>> mat = mat * 2 # second row >>> mat [[0, 0], [0, 0]] >>> mat[0][0] = 'Spam' >>> mat [['Spam', 0], ['Spam', 0]] >>> Does this clarify your doubt? -- Senthil _______________________________________________ BangPypers mailing list BangPypers@python.org http://mail.python.org/mailman/listinfo/bangpypers