Python – Join Tuples
What Does “Join Tuples” Mean?
Joining tuples means combining two or more tuples into a single tuple. Since tuples are immutable, a new tuple is created when joining them.
1. Joining Two Tuples Using +
Operator
You can use the +
operator to join two or more tuples.
Example:
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
result = tuple1 + tuple2
print(result)
Output:
('a', 'b', 'c', 1, 2, 3)
2. Joining More Than Two Tuples
You can join multiple tuples at once using +
.
Example:
t1 = ("x",)
t2 = ("y",)
t3 = ("z",)
joined = t1 + t2 + t3
print(joined)
Output:
('x', 'y', 'z')
3. Repeating Tuple with *
Operator (Not Joining, But Useful)
Although not joining, this is sometimes used to repeat a tuple's elements.
Example:
tuple1 = ("hello",)
result = tuple1 * 3
print(result)
Output:
('hello', 'hello', 'hello')
4. Using a Loop to Join Tuples Dynamically
You can also join tuples inside a loop or from a list of tuples.
Example:
tuples = [("a",), ("b",), ("c",)]
result = ()
for t in tuples:
result += t
print(result)
Output:
('a', 'b', 'c')
5. Edge Case: Joining an Empty Tuple
Joining an empty tuple doesn't change the result.
Example:
empty = ()
t = ("Python",)
print(t + empty)
print(empty + t)
Output:
('Python',)
('Python',)
Summary
Operation | Description |
---|---|
tuple1 + tuple2 | Joins two tuples |
tuple * n | Repeats tuple elements n times |
Loop with += | Useful when joining dynamic tuple list |
Empty tuple join | No effect on result |