I'm trying to write a matrix (2d list) transpose function for fun, and while working on it I came across this very weird behavior. To me the following functions are pretty much identical (except the other has hard-coded the form of the resulting new
list).
def transpose1(mat):
new = [[None] * len(mat)] * len(mat[0])
print("input1:", mat)
print("new1:", new)
for j, line in enumerate(mat):
for i, elem in enumerate(line):
new[i][j] = mat[j][i]
return new
def transpose2(mat):
# only line that differs, but still when
# printing 'new' they seem identical
new = [[None, None], [None, None], [None, None]]
print("input2:", mat)
print("new2:", new)
for j, line in enumerate(mat):
for i, elem in enumerate(line):
new[i][j] = mat[j][i]
return new
mat = [[4, 5, 6], [7, 8, 9]]
print("result1:", transpose1(mat))
print()
print("result2:", transpose2(mat))
Output:
input1: [[4, 5, 6], [7, 8, 9]] new1: [[None, None], [None, None], [None, None]] result1: [[6, 9], [6, 9], [6, 9]] input2: [[4, 5, 6], [7, 8, 9]] new2: [[None, None], [None, None], [None, None]] result2: [[4, 7], [5, 8], [6, 9]]
I just don't understand what difference can the declaration of the new
lists make to the output. Why does the transpose1
function give the wrong result, even though the intermediate new
list looks identical in both cases and the rest of the code is the same?