Python | Print diagonals of 2D list
Given a 2D list (with equal length of sublists), write a Python program to print both the diagonals of the given 2D list.
Examples:
Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output : Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
Input : [['a', 'b'], ['c', 'd']]
Output : Diagonal 1 - ['a', 'd']
Diagonal 2 - ['b', 'c']Approach #1 : Using Python xrange()
We can use one-liner list comprehension along with xrange() function. xrange() is used to iterate a certain number of times in for loops. Thus, we print the element at [i][i] position in every iteration of loop. [Works in Python2]
Python
# Python2 program to print diagonals in 2D listdef printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 -'), print([lst[i][i] for i in xrange(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 -'), print([lst[i][len(lst)-1-i] for i in xrange(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst) |
Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7]
Approach #2 : Using range()
This method is similar to Approach #1. The advantage of range() is that it works for both the versions of Python i.e. Python2 and Python3.
Python3
# Python3 program to print diagonals in 2D listdef printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end ="") print([lst[i][i] for i in range(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 - ', end ="") print([lst[i][len(lst)-i-1] for i in range(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst) |
Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7]
Approach #3 : Using enumerate()
Python enumerate() is also an alternative to above mentioned methods. It uses two variable ‘i’ and ‘r’ two traverse through enumerate(lst) and simply return the ith element of ‘r’.
Python3
# Python3 program to print diagonals in 2D listdef printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end ="") print([r[i] for i, r in enumerate(lst)]) # To print Secondary Diagonal print('Diagonal 2 - ', end ="") print([r[~i] for i, r in enumerate(lst)]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst) |
Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7]


