Open In App

Python – Convert Matrix to Custom Tuple Matrix

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 applications 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 the above further functionalities can be used to solve this problem. In this, we perform the task of binding custom value to each element of the row using g zip(). This is a 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)]

Time complexity: O(n^2) where n is the size of the input matrix. 
Auxiliary space: O(n^2) as well, because the result list “res” stores n^2 elements, where n is the size of the input matrix.

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)]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #3: Using for loop

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
 
# 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
res = []
for i in range(0, len(add_list)):
    for j in range(0, len(test_list[i])):
        res.append((add_list[i], test_list[i][j]))
 
# 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 4: Using the itertools.chain and zip functions from the itertools module

  1. The convert_to_tuples function takes two inputs, a 2D list test_list and a list add_list.
  2. The itertools.chain.from_iterable function is used to create a flattened 1D list of add_list and test_list.
  3. The zip function is used to create tuples of the form (add_list[i], val) for each item in test_list.
  4. The result is a 1D list of tuples.

Python3




import itertools
 
 
def convert_to_tuples(test_list, add_list):
    return list(zip(itertools.chain.from_iterable([[val] * len(add_list) for val in add_list]), itertools.chain.from_iterable(test_list)))
 
# Main
 
 
def main():
 
    # Input list
    test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
    add_list = ['Gfg', 'is', 'best']
 
    result = convert_to_tuples(test_list, add_list)
    print("Result:", result)
 
 
if __name__ == '__main__':
    main()


Output

Result: [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Time complexity: O(n) where n is the total number of elements in test_list. This is because each element in test_list is processed once.
Auxiliary space: O(n) as well, because the result list contains n tuples, where n is the total number of elements in test_list.

Method #5: Using Numpy and broadcasting

Explanation:

  • First, we import numpy library to use its broadcast_to() and array() functions.
  • Next, we initialize the input lists.
  • We use the broadcast_to() function to expand the add_list array along the rows, so that it becomes a matrix with the same number of rows as test_list and the same number of columns as the length of each sublist of test_list. The [:, None] is used to make sure that the array is broadcasted along the columns.
  • Then, we flatten the resulting array and test_list and use zip() to create the custom tuple matrix.
  • Finally, we print the result.

Python3




import numpy as np
 
# 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
res = np.broadcast_to(
    np.array(add_list)[:, None], (len(add_list), len(test_list[0])))
res = list(zip(res.flatten(), np.array(test_list).flatten()))
 
# 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)]

Time complexity: O(N^2) because it involves two loops, one for iterating over the add_list and another for iterating over the test_list.

Auxiliary space: O(N^2) because we create a numpy array to store the broadcasted add_list and a list to store the resulting custom tuple matrix.



Previous Article
Next Article

Similar Reads

Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python - Convert Nested Tuple to Custom Key Dictionary
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this t
4 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read