for i in range(n): for j in range(n): a, b = matrix[i][j], matrix[j][i] matrix[i][j] = b…
- User
for i in range(n): for j in range(n): a, b = matrix[i][j], matrix[j][i] matrix[i][j] = b matrix[j][i] = a
why this isn't swapping
- Assistant
Your code isn’t swapping because both matrix[i][j] and matrix[j][i] get overwritten during the same iteration. Example for a 2×2 case:
First loop: (i=0, j=1) swaps (0,1) with (1,0).
Later loop: (i=1, j=0) swaps them again, undoing the first swap.
Also, when i == j (diagonal elements), you’re swapping an element with itself — which is harmless but unnecessary. To fix it, only loop over half the matrix above the diagonal: pythonCopyEditfor i in range(n): for j in range(i+1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
This way:
Each pair is swapped exactly once.
No element is swapped back in a later iteration.
Diagonal elements are skipped.
If you want, I can also show you how to do it in-place for a transpose in a single pass.