Python Program for Program to Print Matrix in Z form (original) (raw)

Given a square matrix of order n × n, the task is to print its elements in Z form that is, print the first row, then the opposite diagonal (from top-right to bottom-left), and finally the last row of the matrix. For Example:

**Input: [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
**Output: 1 2 3 5 7 8 9

Let's explore different methods to print the matrix in Z form in Python.

Using NumPy

This method uses NumPy’s advanced indexing to directly extract the first row, reverse diagonal, and last row in a single optimized line without explicit loops.

Python `

import numpy as np arr = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]]

m = np.array(arr) print(*m[0], *np.diag(np.fliplr(m))[1:-1], *m[-1])

`

Output

4 5 6 8 3 8 1 8 7 5

**Explanation:

Using List Comprehension

This approach combines rows and diagonals in a single list using list comprehension. It collects all required elements in order and prints them together fast and clean without extra loops.

Python `

arr = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]]

n = len(arr) res = [*arr[0], *[arr[i][n - i - 1] for i in range(1, n - 1)], *arr[-1]] print(*res)

`

Output

4 5 6 8 3 8 1 8 7 5

**Explanation:

Using Flattened Index Access

This method flattens the matrix into a single list and computes exact indices for the top row, diagonal, and bottom row, then prints those elements sequentially.

Python `

arr = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]]

n = len(arr) flt = sum(arr, []) ind = list(range(n)) + [i * n + (n - i - 1) for i in range(1, n - 1)] + [n * (n - 1) + j for j in range(n)] print(*[flt[i] for i in ind])

`

Output

4 5 6 8 3 8 1 8 7 5

**Explanation:

Using Index-Based Traversal

This method uses nested loops to traverse each required position step by step first printing the top row, then the diagonal, and finally the bottom row in order.

Python `

arr = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]]

n = len(arr[0])

Print first row

for j in range(n): print(arr[0][j], end=" ")

Print opposite diagonal

for i in range(1, n - 1): print(arr[i][n - i - 1], end=" ")

Print last row

for j in range(n): print(arr[n - 1][j], end=" ")

`

Output

4 5 6 8 3 8 1 8 7 5

**Explanation:

Please refer complete article on Program to Print Matrix in Z form for more details!