0

So I have this simple code:

list = [[1,2],[4,5]]
list1 = list.copy() 
for i in range(len(list)):
    for j in range(len(list[i])):
        print(i,j, ":", list[i][j], "and", j,i, ":", list1[j][i])
        nr = input('Line {0}, Column{1}: ' .format(i+1, j+1) )
        list[i][j] = nr
        list1[j][i] = nr
        print(list,list1)
print(list1, list)

If I want the final result of the variable list to be the following matrix: [[1,2],[3,4]], so the variable list1 should be the transposed matrix: [[1,3],[2,4]]. Somehow the result is this: [['1', '3'], ['3', '4']] [['1', '3'], ['3', '4']]. Please someone help me. Thanks and have a good weekend

  • Why did you bother creating a copy of a list if you're going to just overwrite every element in the list? – shrewmouse Dec 11 '21 at 13:45
  • @shrewmouse Because I think is the easiest way instead of appending everytime elements and lists to the *list1*. For example, if the value of *list* is something like this: [[x,y],[z,k]]. The *list1* will be [[x,y],[z,k]] and I just need to change the indexes to have the correct value: [[x,z],[y,k]] (transposed matrix of [[x,y],[z,k]]). Don't you think ? – Tomasnborges Dec 11 '21 at 15:38

1 Answers1

1

you should use copy.deepcopy.

If your list is a list of integers or floats, copy would suffice but since you have list of lists, you need to recursively copy the elements inside the lists.

You can find more detailed answer here: What is the difference between shallow copy, deepcopy and normal assignment operation?

MoneyBall
  • 2,343
  • 5
  • 26
  • 59