The Wayback Machine - https://web.archive.org/web/20240909225557/https://www.geeksforgeeks.org/python-convert-matrix-to-custom-tuple-matrix/
Open In App

Python – Convert Matrix to Custom Tuple Matrix

Last Updated : 28 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Tuple within a Tuple in Python
In the realm of Python programming, tuples offer a flexible solution for organizing data effectively. By allowing the inclusion of other tuples within them, tuples further enhance their capabilities. In this article, we will see how we can use tuple within a tuple in Python. Using Tuple within a Tuple in PythonBelow are some of the ways by which we
4 min read
Python - Add Custom Column to Tuple list
Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_list = [(3, ), (7, ), (2, )] cus_eles = [7, 8, 2] Output : [(3, 7), (
5 min read
Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let's discuss certain ways in which this task can be p
7 min read
Sort a Tuple of Custom Objects by Properties in Python
We are given a tuple of custom objects and our task is to sort a tuple of custom objects by properties in Python and print the result. In this article, we will see how to sort a tuple of custom objects by properties in Python. Example: Input: CustomObject("Alice", 30), CustomObject("Bob", 25), CustomObject("Charlie", 35)Output: Bob 25 Alice 30 Char
3 min read
Python - Convert Matrix to overlapping Tuple Pairs
Sometimes, while working with Python data, we can have a problem in which we need to perform overlap of elements in Matrix, and convert them as tuple pairs. This kind of problem can occur in various application in data domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [[5, 6, 3], [8, 6, 2], [2, 5, 1]] Outpu
5 min read
Python | Convert String to tuple list
Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a brute force method to perform this task. In this, we
5 min read
Python | Program to convert a tuple to a string
Given a tuple of characters, Write a python program to convert the tuple into a string. Examples: Input : ('a', 'b', 'c', 'd', 'e') Output : abcde Input : ('g', 'e', 'e', 'k', 's') Output : geeks Approach 1: using simple for loop Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to
4 min read
Python | Convert a list into tuple of lists
We are given a list, the task is to convert the list into tuple of lists. Input: ['Geeks', 'For', 'geeks'] Output: (['Geeks'], ['For'], ['geeks'])Input: ['first', 'second', 'third'] Output: (['first'], ['second'], ['third']) Method #1: Using Comprehension C/C++ Code # Python code to convert a list into tuple of lists # Initialisation of list Input
4 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Python | Convert list to indexed tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to convert a list to tuple. This kind of problem have been dealt with before. But sometimes, we have it's variation in which we need to assign the index of the element along with element as a tuple. Let's discuss certain ways in which this task can be performed. Meth
3 min read
Python | Convert tuple records to single string
Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it's to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let's discuss certain ways in which this problem can be solved Method #1: Using join() + list compr
6 min read
Python | Convert location coordinates to tuple
Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + float() + split() + map() The combination of above fun
5 min read
Python | Convert Integral list to tuple list
Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension List comprehension can be
3 min read
Python | Convert tuple to float value
Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Let's discuss certain way in which this can be achieved. Method : Using join() + float() + str() + generator expression The combination of
3 min read
Python | Convert tuple to adjacent pair dictionary
Sometimes, while working with records, we can have a problem in which we have data and need to convert to key-value dictionary using adjacent elements. This problem can have application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using dict() + dictionary comprehension + slicing The above f
5 min read
Python | Convert String to Tuple
Interconversion of data types is very common problem one can face while programming. There can be a problem in which we need to convert a string of integers to a tuple. Let's discuss certain ways in which this can be done. Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split
8 min read
Python | Convert String to N chunks tuple
Sometimes, while working with Python Strings, we can have a problem in which we need to break a string to N sized chunks to a tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple This is one approach in which this task can be performed. In this, we just iterate the String and break the
2 min read
Python | Convert Tuple to integer
Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let's discuss certain ways in which this task can be performed. Method #1 : Using reduce() + lambda The combination of above functions can be used to perform this task. In this, we use lambda function to perform logi
5 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read