Print diagonals of 2d list in Python
In this tutorial, you will learn how to print diagonals of 2d list in Python.
To print the diagonals of a 2d list in Python, we need to iterate through the elements of the diagonals and collect them into a list.
As all the diagonal elements have the same row number and column number we need to identify those elements and print those elements which become the diagonals of the list.
Here’s a step-by-step procedure to do this:
1. Identify the Diagonals of the 2d list:
The main diagonal of the matrix consists of the same row number and column number(For example: [0][0], [1][1], [2][2], etc).
2. Initialize the Matrix:
Initialize a 2 dimensional matrix to work with
m = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
3. Determine the Size of the Matrix:
To handle the matrices that have different number of rows and columns, find the minimum dimension
size=min(len(m), len(m[0]))
This makes sure that when you access the diagonal elements, you do not go out of bounds
4. Retrieve the Diagonal Elements:
Collect the elements where the row index is equal to the column index using the List comprehension
diagonal=[m[i][i] for i in range (size)]
This iterates from the first element i.e., [0] to the last element i.e., [n-1].
For example: It will pick the elements such as m[0][0], m[1][1], m[2][2], etc.
5. Print the Diagonal Elements of the 2d Matrix:
Now, print the elements that are collected
print("Diagonal elements of the Matrix are:", diagonal)
Complete code:
def print_diagonal(m): size = min(len(m), len(m[0])) diagonal = [m[i][i] for i in range(size)] print("Diagonal elements of the Matrix are:", diagonal) # Example m = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print_diagonal(m)
Output:
Diagonal elements of the Matrix are: [1, 5, 9]
The diagonals of a 2d matrix can be easily retrieved and printed using this simple and straightforward approach.
This is an additional example of learning this problem
You may also refer to and learn:
Leave a Reply