Table of Contents
ToggleJoining tuples in Python refers to combining multiple tuples into a single tuple using various techniques.
The concatenation operator (+) allows merging tuples by joining their elements into a new tuple.
T1 = (10, 20, 30, 40)
T2 = ('one', 'two', 'three', 'four')
joined_tuple = T1 + T2
print("Joined Tuple:", joined_tuple)
Output: (10, 20, 30, 40, ‘one’, ‘two’, ‘three’, ‘four’)
List comprehension enables tuple merging by iterating over multiple tuples and creating a new list.
T1 = (36, 24, 3)
T2 = (84, 5, 81)
joined_tuple = [item for subtuple in [T1, T2] for item in subtuple]
print("Joined Tuple:", joined_tuple)
Output: [36, 24, 3, 84, 5, 81]
The extend() function allows merging tuples by converting them into lists and then back into a tuple.
T1 = (10, 20, 30, 40)
T2 = ('one', 'two', 'three', 'four')
L1 = list(T1)
L2 = list(T2)
L1.extend(L2)
T1 = tuple(L1)
print("Joined Tuple:", T1)
Output: (10, 20, 30, 40, ‘one’, ‘two’, ‘three’, ‘four’)
The sum() function merges numeric tuples by summing their elements into a new tuple.
T1 = (10, 20, 30, 40)
T2 = ('one', 'two', 'three', 'four')
T3 = sum((T1, T2), ())
print("Joined Tuple:", T3)
Output: (10, 20, 30, 40, ‘one’, ‘two’, ‘three’, ‘four’)
A for loop iterates through elements in one tuple and appends them to another using +=.
T1 = (10, 20, 30, 40)
T2 = ('one', 'two', 'three', 'four')
for t in T2:
T1 += (t,)
print(T1)
Output: (10, 20, 30, 40, ‘one’, ‘two’, ‘three’, ‘four’)
