-1
    def add_column(matrix):
"""
  >>> m = [[0, 0], [0, 0]]
  >>> add_column(m)
  [[0, 0, 0], [0, 0, 0]]
  >>> n = [[3, 2], [5, 1], [4, 7]]
  >>> add_column(n)
  [[3, 2, 0], [5, 1, 0], [4, 7, 0]]
  >>> n
  [[3, 2], [5, 1], [4, 7]]
"""
new_matrix = matrix[:]
for row in new_matrix:
    row += [0]
return new_matrix

Doctests to return the original matrix will return the new matrix, I'm not sure how to clone this matrix without editing the original.

2 Answers2

1

You are making a copy of the outer list, but each inner list is still the same. You need to use a different list for row instead of modifying it:

new_matrix = []
for row in matrix:
    new_matrix.append(row + [0])

A condensed version of that is:

new_matrix = [row + [0] for row in matrix]
zondo
  • 19,901
  • 8
  • 44
  • 83
1

The problem arises because the matrix is represented as a list of lists. The statement new_matrix = matrix[:] makes a copy of the "outer" list but does not make a copy of each row. Your implementation is also known as a shallow copy. See this post for a more detailed explanation.

You can either implement the add_column method following zondo's suggestion, use the copy module to create a deep copy, or use numpy. Although using numpy requires you to get to know a new library, the flexibility and computational efficiency is worth it in the long run.

Community
  • 1
  • 1
Till Hoffmann
  • 9,479
  • 6
  • 46
  • 64