Python | Print diagonals of 2D list

Examples :

  Input:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  Output:  Diagnol 1 - [1, 5, 9] Diagnol 2 - [3, 5, 7]  Input:  [['a',' b' ], ['c',' d']]  Output:  Diagnol 1 - ['a',' d'] Diagnol 2 - ['b',' c'] 

Approach # 1 Using Python xrange()

We can use a one-line list comprehension along with the xrange () function xrange () is used to iterate over a certain number of for loops. Thus, we print the element at position [i] [i] at each iteration of the loop. [Works in Python2]

Exit :

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

Approach # 2 Use Using range()

This method is similar to approach # 1. The advantage of range () is that it works for both versions of Python, i.e. .e. Python2 and Python3.

# Python2 program for printing diagonals in 2D list

 

def printDiagnol (lst):

# To print initial diagnostics

print ( 'Diagnol 1 -' ),

print ([ lst [i] [i] for i in xrange ( len (lst) )])

  

# Printable Secondry Diagnol

print ( ' Diagnol 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 ]]

 
printDiagnol (lst)

# Python3 program for printing diagonals in 2D list

  

def printDiagnol (lst):

 

# To print initial diagnostics

print ( ' Diagnol 1 - ' , end = " ")

print ([lst [i ] [i] for i in range ( len (lst))])

 

# Printable Secondry Diagnol

print ( ' Diagnol 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 ]]

printDiagnol (lst)

Output:

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

Approach # 3. Using enumerate ()

Python enumerate () is also an alternative to the above methods. It uses two variables & # 39; i & # 39; and & # 39; r & # 39;, go through the enum (lst) and just return the i- th element from & # 39; r & # 39 ;.

# Python3 program for printing diagonals in a 2D list

 

def printDiagnol (lst):

# To print initial diagnostics

print ( 'Diagnol 1 -' , end = "")

print ([r [i] for i, r in   enumerate (lst)])

 

# For printing secondary diagnostics

print ( ' Diagnol 2 - ' , end = "")

print ([r [~ i] for i, r in enumerate (lst)])

 

  
# Driver code

lst = [[< / code> 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]

printDiagnol (lst)

Output:

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




Get Solution for free from DataCamp guru