How Does List.append() Work In Python - I'm Getting An Unexpected Result
Solution 1:
Key point is to make a copy of inner list and then append in the outer list.
copy = t_list[::]
It is because list is an object and it is a refresnce. so when you append another item in a list, it will be updated over all places where that objects exists. In your case, you are appending list into a list and then updating the inner list which causes the previous list items to update as well. You need to append a copy of a list in transposed
list. Here is a solution.
transposed = []
for i in range(4):
print("i", i)
t_list = []
for row in matrix:
print("row", row)
t_list.append(row[i])
print("t_list**********", t_list)
transposed.append(t_list[::])
print("transposed//////////////", transposed)
Solution 2:
It seems like an indentation issue in the line transposed.append(t_list)
:
transposed = []
for i in range(4):
t_list = []
for row in matrix:
t_list.append(row[i])
transposed.append(t_list)
This code prints:
[[1, 5, 9],
[2, 6, 10],
[3, 7, 11],
[4, 8, 12]]
Transpose has been implemented in numpy and it works with python arrays:
import numpy as np
np.transpose(matrix)
Solution 3:
The problem is here:
t_list = []
for row in matrix:
t_list.append(row[i])
transposed.append(t_list)
Inside the loop the contents of the list object t_list
changes, but the
list object itself remains the same. Thus, transposed
gets the same object
for each row.
This is fixed by appending a copy of the current list instead of the original list object.
transposed.append(list(t_list))
Post a Comment for "How Does List.append() Work In Python - I'm Getting An Unexpected Result"