Q:

Python program to convert tuple matrix to tuple list

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to convert tuple into list by addin... >>
<< Python program to convert binary tuple to integer...