440,096 Members | 1,568 Online
Need help? Post your question and get tips & solutions from a community of 440,096 IT Pros & Developers. It's quick & easy.

# basic python question about lists and matrices

 P: 4 I'm learning python through the "How to think like a computer scientist" book. There is a certain exercise that multiplies a matrix m by a scalar n: Expand|Select|Wrap|Line Numbers def scalar_mult(n, m):  """     >>> a = [[1, 2], [3, 4]]     >>> scalar_mult(3, a)     [[3, 6], [9, 12]]     >>> b = [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2,2, 3]]     >>> b     [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]]     >>> scalar_mult(10, b)     [[30, 50, 70], [10, 10, 10], [0, 20, 0], [20,20, 30]]     >>> b     [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]] """     new_matrix = []     for row in m:         new_row = []                 for value in row:             new_row += [value*n]         new_matrix += [new_row]     return new_matrix       above is the correct code. Now, can someone explain why I get : >>> b [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]] scalar_mult(10, b) Expected: [[30, 50, 70], [10, 10, 10], [0, 20, 0], [20, 20, 30]] Got: [[30, 50, 70, 10, 10, 10, 0, 20, 0, 20, 20, 30], [30, 50, 70, 10, 10, 10, 0, 20, 0, 20, 20, 30], [30, 50, 70, 10, 10, 10, 0, 20, 0, 20, 20, 30], [30, 50, 70, 10, 10, 10, 0, 20, 0, 20, 20, 30]] when the code is written as follows: Expand|Select|Wrap|Line Numbers new_matrix = [] new_row = []      for row in m:              for value in row:             new_row += [value*n]         new_matrix += [new_row]     return new_matrix     what exactly happens when I move new_row = [] above "for row in m:" ? Jan 4 '11 #1