Open In App

Python Program to Convert Tuple Matrix to Tuple List

Last Updated : 24 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 column number elements contained together.

Convert Tuple Matrix to Tuple List Using list comprehension + zip()

In this, we perform task of flattening using list comprehension and zip() is used to perform column pairing to render as tuple pairs. 

Steps:

  1. The program initializes a list called test_list with three elements, each of which is a list of tuples.
  2. It prints the original list using the print() function and string concatenation.
  3. The program uses a list comprehension to flatten the test_list. The ele variable represents each individual element in the sublists, while the sub variable represents each sublist in the test_list. The flattened list is stored in the variable temp.
  4. The program uses the zip() function to join the tuples in temp into column pairs, which are then stored in the variable res. Note that the * operator is used to unpack the elements in temp as arguments to zip().
  5. The program prints the result using the print() function and string concatenation.

Python3




# Python3 code to demonstrate working of
# Convert Tuple Matrix to Tuple List
# Using list comprehension + zip()
 
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# flattening
temp = [ele for sub in test_list for ele in sub]
 
# joining to form column pairs
res = list(zip(*temp))
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original list is : [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
The converted tuple list : [(4, 7, 10, 18, 0, 10), (5, 8, 13, 17, 4, 1)]

Convert Tuple Matrix to Tuple List Using chain.from_iterable() + zip()

In this, task of flattening is performed using chain.from_iterable() and zip() is used to perform the task of column pairing.

Python3




# Python3 code to demonstrate working of
# Convert Tuple Matrix to Tuple List
# Using chain.from_iterable() + zip()
from itertools import chain
 
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# flattening using from_iterable
res = list(zip(*chain.from_iterable(test_list)))
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original list is : [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
The converted tuple list : [(4, 7, 10, 18, 0, 10), (5, 8, 13, 17, 4, 1)]

Time complexity: O(nm)
Auxiliary space: O(nm),

Convert Tuple Matrix to Tuple List Using extend(),list() and tuple() methods

Python3




# Python3 code to demonstrate working of
# Convert Tuple Matrix to Tuple List
 
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
x=[]
for i in test_list:
    for j in i:
        j=list(j)
        x.extend(j)
re1=[]
re2=[]
for i in range(0,len(x)):
    if(i%2==0):
        re1.append(x[i])
    else:
        re2.append(x[i])
res=[]
res.append(tuple(re1))
res.append(tuple(re2))
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original list is : [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
The converted tuple list : [(4, 7, 10, 18, 0, 10), (5, 8, 13, 17, 4, 1)]

The time complexity is O(n^2), where n is the total number of elements in the input matrix. 
The auxiliary space complexity of this code is O(n), as it uses a list x to store all the elements in the matrix and two lists re1 and re2 to store the elements after converting them to a tuple list.

Convert Tuple Matrix to Tuple List Using lambda function 

This code converts a matrix represented as a tuple of tuples, matrix, into a tuple of lists, list_tuple. It uses map() and a lambda function to apply list() to each tuple in matrix, converting them into lists. The resulting tuple of lists is then printed.

Python3




matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
 
list_tuple = tuple(map(lambda x: list(x), matrix))
 
print(list_tuple)  # Output: ([1, 2, 3], [4, 5, 6], [7, 8, 9])


Output

([1, 2, 3], [4, 5, 6], [7, 8, 9])

Time complexity: O(mn), where m is the number of rows in the matrix and n is the number of columns in the matrix. This is because the map function is applied to each inner tuple in the matrix, and converting each inner tuple to a list takes O(n) time. Since there are m inner tuples, the total time complexity is O(mn).
Auxiliary space: O(mn), which represents the memory used to store the final tuple of lists. This is because each inner tuple is converted to a list, and all the lists are stored in the final tuple. The amount of memory used is proportional to the size of the matrix.

Convert Tuple Matrix to Tuple List Using NumPy module

Step-by-step algorithm:

  1. Initialize the list test_list with the given input.
  2. Create a numpy array by flattening test_list into a 1-dimensional array of integers using a list comprehension and the numpy function array. 
  3. The data type is specified as np.int64.
  4. Transpose the array using the numpy function T.
  5. Convert the transposed array into a list of tuples using the tuple and map functions.
  6. Assign the resulting list of tuples to the variable result.
  7. Print the final result.

Python3




import numpy as np
 
# Initialize the list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
 
# Flatten the list and convert it to a numpy array
array = np.array([col for sublist in test_list for col in sublist], np.int64)
 
# Transpose the array and convert it to a tuple
result = tuple(map(tuple, array.T))
 
# Print the result
print("The converted tuple list:", result)


output:

The converted tuple list : [([4, 10, 0], [7, 18, 10]), ([5, 13, 4], [8, 17, 1])

Time complexity: O(n), where n is the total number of elements in the input list test_list. This is because the algorithm involves iterating over each element in the list once to flatten it into a 1-dimensional numpy array, then transposing the array, and finally converting the transposed array into a list of tuples. The time complexity of these operations is linear with respect to the number of elements in the input list.
Auxiliary space: O(n), where n is the total number of elements in the input list test_list. This is because the algorithm creates a numpy array of the same size as the flattened input list, which requires additional memory. The space used by the result variable is also proportional to the number of elements in the input list. Overall, the space complexity of the algorithm is linear with respect to the number of elements in the input list.

Convert Tuple Matrix to Tuple List Using Recursive method.

Step-by-step algorithm:

  1. Define a function flatten(lst) that takes a list as input.
  2. If the input list lst is a list, then recursively flatten each sublist within lst using a list comprehension that iterates over each sublist element and applies the flatten() function to it. If the element is not a list, then simply return the element as a list.
  3. Once all the sublists have been flattened, concatenate them into a single list using another list comprehension.
  4. Convert the flattened list of tuples into a list of columns by using the zip() function with the * operator to unpack the tuples into separate arguments for zip().
  5. Return the resulting list of columns.

Python3




# define a recursive function to flatten the list
def flatten(lst):
    if isinstance(lst, list):
        return [ele for sub in lst for ele in flatten(sub)]
    else:
        return [lst]
 
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# flattening and converting to tuple list
temp = flatten(test_list)
res = list(zip(*temp))
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original list is : [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
The converted tuple list : [(4, 7, 10, 18, 0, 10), (5, 8, 13, 17, 4, 1)]

Time complexity: O(n), where n is the total number of elements in the input list. 
Auxiliary space: O(n), since the flatten () function creates a new list containing all the elements of the input list.



Previous Article
Next Article

Similar Reads

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 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 applications in data domains as Matrix is integral DS that is used. Let's discuss certain ways in which this task ca
6 min read
Python Program to Convert Tuple Value List to List of Tuples
Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples. Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] Explanation : Keys grouped with values.Convert Tuple Value List to List of Tuples Using loop + * operator + items() This is
8 min read
Python program to convert a list of strings with a delimiter to a list of tuple
Given a List containing strings with a particular delimiter. The task is to remove the delimiter and convert the string to the list of tuple. Examples: Input : test_list = ["1-2", "3-4-8-9"], K = "-" Output : [(1, 2), (3, 4, 8, 9)] Explanation : After splitting, 1-2 => (1, 2). Input : test_list = ["1*2", "3*4*8*9"], K = "*" Output : [(1, 2), (3,
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
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 | 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 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
three90RightbarBannerImg