Python – Convert Matrix to Custom Tuple Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have application in data domains as Matrix is integral DS that is used. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[4, 5], [7, 3]], add_list = [‘Gfg’, ‘best’] Output : [(‘Gfg’, 4), (‘Gfg’, 5), (‘best’, 7), (‘best’, 3)] Input : test_list = [[4, 5]], add_list = [‘Gfg’] Output : [(‘Gfg’, 4), (‘Gfg’, 5)]
Method #1 : Using loop + zip() The combination of above functionalities can be used to solve this problem. In this, we perform the task of binding custom value to each element of row using zip(). This is brute force way to perform this task.
Method #2 : Using list comprehension + zip() This is yet another way in which this task can be performed. In this, we perform a similar task as the above method, just as a shorthand.
The Time and Space Complexity is the same for both methods:
Time Complexity: O(n2)
Space Complexity: O(n)