# Python Program to Interchange elements of first and last rows in matrix

• Last Updated : 24 May, 2022

Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.
Examples :

```Input : 3 4 5 0
2 6 1 2
2 7 1 2
2 1 1 2
Output : 2 1 1 2
2 6 1 2
2 7 1 2
3 4 5 0

Input : 9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output : 1 2 3 1
2 3 4 1
5 6 6 5
9 7 5 1```

The approach is very simple, we can simply swap the elements of first and last row of the matrix inorder to get the desired matrix as output.
Below is the implementation of the approach :

## Python3

 `# Python code to swap the element``# of first and last row and display``# the result` `def` `interchangeFirstLast(mat, n, m):``    ``rows ``=` `n``    ` `    ``# swapping of element between``    ``# first and last rows``    ``for` `i ``in` `range``(n):``        ``t ``=` `mat[``0``][i]``        ``mat[``0``][i] ``=` `mat[rows``-``1``][i]``        ``mat[rows``-``1``][i] ``=` `t` `# Driver Program``mat ``=` `[[``8``, ``9``, ``7``, ``6``],``          ``[``4``, ``7``, ``6``, ``5``],``       ``[``3``, ``2``, ``1``, ``8``],``       ``[``9``, ``9``, ``7``, ``7``]]` `n ``=` `4``m ``=` `4``interchangeFirstLast(mat, n, m)` `# printing the interchanged matrix``for` `i ``in` `range``(n):``    ``for` `j ``in` `range``(m):``        ``print``(mat[i][j], end ``=` `" "``)``    ``print``("``")` `# This code is contributed by Shrikant13.`

Output :

```9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6 ```

Time Complexity: O(N)

Auxiliary Space: O(1)

Please refer complete article on Interchange elements of first and last rows in matrix for more details!

My Personal Notes arrow_drop_up