Given a two-dimensional list of integers, write a Python program to get the transpose of given list of lists.
In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix. For example m = [[10, 20], [40, 50], [30, 60]] represents a matrix of 3 rows and 2 columns. First element of the list – m[0] and element in first row, 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
def transpose(l1, l2):
for i in range ( len (l1[ 0 ])):
row = []
for item in l1:
row.append(item[i])
l2.append(row)
return l2
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]]
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The loops is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(1) constant additional space is required
Method #2: Using List comprehensions
Python
def transpose(l1, l2):
l2 = [[row[i] for row in l1] for i in range ( len (l1[ 0 ]))]
return l2
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]]
Time complexity: The nested loop used in the list comprehension has a time complexity of O(n^2) where n is the size of the input list
Auxiliary space: The space used in the function is the space required to create a new list l2, which is the size of the input list l1 in reverse order.
Method #3: Using numpy
Python3
import numpy
l1 = [[ 4 , 5 , 3 , 9 ], [ 7 , 1 , 8 , 2 ], [ 5 , 6 , 4 , 7 ]]
print (numpy.transpose(l1))
|
Output:
[[4 7 5]
[5 1 6]
[3 8 4]
[9 2 7]]
Method #4: Using zip function
Python
def transpose(l1, l2):
l2 = list ( map ( list , zip ( * l1)))
return l2
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]]