Python | Transpose elements of a two-dimensional list

In Python, a matrix can be interpreted as a list of lists. Each element is considered as a row of the matrix. For example, m = [[10, 20], [40, 50], [30, 60]] is a matrix of 3 rows and 2 columns. The first item in the list — m [0] and the item on the first row, the first column — m [0] [0].

Example :

  Input:  l1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]  Output:  lt = [[4, 7, 5], [5, 1, 6] , [3, 8, 4], [9, 2, 7]] 

Method # 1: Using Loops

# Python transpose program
# list items of two dimensions

def transpose (l1, l2):

 

# iterate over the list l1 to the length of the element

for i in range ( len (l1 [ 0 ])):

# print (s)

row = []

for item in l1:

# add to a new list with index values ​​and positions

# i contains index position and element contains values ​​

row.append (item [i])

l2.append (row)

  return l2

 
# Driver code

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

l2 = []

print (transpose (l1, l2))

Exit:

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

Method # 2: Using list views

# Python transpose program
# list items of two dimensions

def transpose (l1, l2):

 

  # we have nested loops in understandings

# i is assigned using inner loop

# then the element value is routed by the string [i]

  # and added to l2

l2 = [[row [i] for row in l1] for i in range ( len (l1 [ 0 ]))]

return l2

  
# Driver code

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

l2 = []

print (transpose (l1, l2))

Output:

 [[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]] < / pre> 

Method # 3: Using NumPy

# Python transpose program
# list items of two dimensions

import numpy 

 

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

print (numpy.transpose (l1)) 

Exit:

 [[4 7 5] [5 1 6] [3 8 4] [ 9 2 7]] 




Get Solution for free from DataCamp guru