Home »
Python »
Python programs
Python program to convert tuple matrix to tuple list
Here, we have a 2-D matrix of tuples and we need to convert this matrix to a 1D tuple list.
Submitted by Shivang Yadav, on September 01, 2021
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
Converting Tuple Matrix to Tuple List
We will be flattening the tuple matrix to the tuple list in python. This is done by iterating over the matrix and zipping together the tuples in the same row and which converts it into a tuple list.
Different methods to perform the task in Python.
Method 1:
One method to perform the task is by using Python's from_iterable() method from chain than using the zip() method.
# Python program to convert tuple matrix
# to tuple list
from itertools import chain
# Initializing matrix list and printing its value
tupleMat = [[(14, 2), (9, 11)], [(1, 0), (8, 12)], [(0, 4), (10, 1)]]
print("Tuple Matrix : " + str(tupleMat))
# Flaterning List
convertedTuple = list(zip(*chain.from_iterable(tupleMat)))
# Printing values
print("Converted list of Tuples : " + str(convertedTuple))
Output:
Tuple Matrix : [[(14, 2), (9, 11)], [(1, 0), (8, 12)], [(0, 4), (10, 1)]]
Converted list of Tuples : [(14, 9, 1, 8, 0, 10), (2, 11, 0, 12, 4, 1)]
Method 2:
Another method that will replace the from_iterable() method is using list Comprehension that will replace the complex code with a single line easy to understand.
# Python program to convert tuple matrix
# to tuple list
from itertools import chain
# Initializing matrix list and printing its value
tupleMat = [[(14, 2), (9, 11)], [(1, 0), (8, 12)], [(0, 4), (10, 1)]]
print("Tuple Matrix : " + str(tupleMat))
# Flaterning List
convertedTuple = list(zip(*[ele for sub in tupleMat for ele in sub]))
# Printing values
print("Converted list of Tuples : " + str(convertedTuple))
Output:
Tuple Matrix : [[(14, 2), (9, 11)], [(1, 0), (8, 12)], [(0, 4), (10, 1)]]
Converted list of Tuples : [(14, 9, 1, 8, 0, 10), (2, 11, 0, 12, 4, 1)]
Python Tuple Programs »