Python Practice › Tuple Programs › Program 14

Add values row by row to a tuple matrix

MediumTuple Programs · 14 of 70

Write a Python program to add one value from a tuple to each row of a tuple matrix.

Advertisement
Input
A = [[("sqa", 4)], [("tools", 8)]], B = (3, 6)
Output
[[('sqa', 4, 3)], [('tools', 8, 6)]]

Approach

  1. Pair each row with its value using zip, then extend every tuple in the row.

Solution

Python
A = [[("sqa", 4)], [("tools", 8)]]B = (3, 6)result = [[t + (value,) for t in row] for row, value in zip(A, B)]print(result)
Output
[[('sqa', 4, 3)], [('tools', 8, 6)]]

Line by line

Line 3

zip(A, B) pairs the first row with 3 and the second with 6; each tuple gets that value appended.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs