The Wayback Machine - https://web.archive.org/web/20220926155907/https://www.geeksforgeeks.org/python-print-diagonals-of-2d-list/
Skip to content
Related Articles

Related Articles

Python | Print diagonals of 2D list

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 30 Aug, 2021
View Discussion
Improve Article
Save Article

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 list
 
def 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 code
lst = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]
 
printDiagonal(lst)

Output

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 list
 
def 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 code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)

Output

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 list
 
def 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 code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)

Output

Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!