Python | Convert to N * N matrix of tuples

Python Methods and Functions

Method # 1: Using * operator loop + * operator
This problem can be solved with a loop. It is a brute force method to accomplish this task. We just add the default as many times as there is no data in the row than N.

# Python3 code to demonstrate how it works
# Convert to N * N matrix of tuples
# using loop + * statement

 
# initialize tuple

test_tup = (( 5 , 4 ), ( 3 ,), ( 1 , 5 , 6 , 7 < / code> ), ( 2 , 4 , 5 ))

 
# print original tuple

print ( " The original tuple is: " + str (test_tup))

  
# dimension initialization

N = 4

 
# Conversion into an N * N matrix of tuples
# using the loop + * operator

res = []

for tup in test_tup:

res.append (tup + ( 0 ,) * (N - len (tup)))

 
# print result

print ( "Tuple after filling values:" + str (res))

Output:

 The original tuple is: ((5, 4), (3,), (1, 5, 6 , 7), (2, 4, 5)) Tuple after filling values: [(5, 4, 0, 0), (3, 0, 0, 0), (1, 5, 6, 7), (2 , 4, 5, 0)] 

Method # 2. Using a tuple () + generator expression
A similar task can be accomplished in one line using a generator expression. This applies the same logic as described above, only as a single line.  tuple () , changes the result to a tuple.

Output:

 The original tuple is: ((5, 4), (3,), (1, 5, 6, 7), (2, 4, 5)) Tuple after filling values: ((5, 4, 0, 0), (3, 0, 0, 0), (1, 5, 6, 7), (2, 4, 5, 0)) 




Get Solution for free from DataCamp guru

# Python3 code to demonstrate how it works
# Convert to N * N matrix of tuples
# using tuple () + expression generator

 
# initialize tuple

test_tup = (( 5 , 4 ), ( 3 ,), ( 1 , 5 , 6 , 7 ), ( 2 , 4 , 5 ))

  
# printing the original tuple

print ( "The original tuple is:" + str (test_tup))

 
# dimension initialization

N = 4

 
# Convert to N * N matrix of tuples
# using tuple () + expression generator

res = tuple (sub + ( 0 ,) * ( N - len (sub)) for sub in test_tup)

 
# print result

print ( "Tuple after filling values:" + str (res))