Skip to content
Related Articles

Related Articles

Python – Convert Matrix to Custom Tuple Matrix

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 10 Jul, 2022
View Discussion
Improve Article
Save Article

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. 

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
  for e in ele:
    res.append((idx, e))
 
# printing result
print("Matrix after conversion : " + str(res))

Output : The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]] Matrix after conversion : [(‘Gfg’, 4), (‘Gfg’, 5), (‘Gfg’, 6), (‘is’, 6), (‘is’, 7), (‘is’, 3), (‘best’, 1), (‘best’, 3), (‘best’, 4)]

  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. 

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
res = [(ele1, ele2) for ele1, sub in zip(add_list, test_list) for ele2 in sub]
 
# printing result
print("Matrix after conversion : " + str(res))

Output : The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]] Matrix after conversion : [(‘Gfg’, 4), (‘Gfg’, 5), (‘Gfg’, 6), (‘is’, 6), (‘is’, 7), (‘is’, 3), (‘best’, 1), (‘best’, 3), (‘best’, 4)]

The Time and Space Complexity is the same for both methods:

Time Complexity: O(n2)

Space Complexity: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!