Search code examples
for-loopmatrixnested-loops

What is the difference between writing in one and two lines when transporting a matrix?


If the replacement of elements is written in two lines, then the matrix is ​​transported incorrectly

x=[[i for i in list(map(int,input().split()))] 
   for _ in range(int(input()))]
print("Result:")
for i in range(len(x)):
    for j in range(i,len(x)):
        if i>0:
            j-=1
        x[i][j]=x[j][i]
        x[j][i]=x[i][j]
[print(*i) for i in x]

Input: 3 1 2 3 4 5 6 7 8 9

Result: 1 4 7 4 5 6 7 6 9

If the replacement of elements is written in one line, then the transportation of the matrix occurs correctly

x=[[i for i in list(map(int,input().split()))] 
   for _ in range(int(input()))]
print("Result:")
for i in range(len(x)):
    for j in range(i,len(x)):
        x[i][j],x[j][i]=x[j][i],x[i][j]
[print(*i) for i in x]

Input: 3 1 2 3 4 5 6 7 8 9

Result: 1 4 7 2 5 8 3 6 9

Why is this happening? I don't understand the difference


Solution

  • Let's simplify this by removing the indices and assigning sample values:

    A = x[i][j] = 4
    B = x[j][i] = 2
    

    Now do your two lines:

    A = B  # what is the value of A now? of B?
    B = A  # what is the value of B now? of A?
    

    A is overwritten with the value of B, then that new value is copied back to B. The original value of A is lost.

    When using one line:

    A, B = B, A
    

    Python (I assume that's the language you use) creates an intermediate tuple that stores the original values of B and A, then swaps them when writing back to A and B