Python Program to Swap Two Tuples

1. Introduction

Swapping values is a fundamental concept in programming. When it comes to tuples in Python, which are immutable, the swapping process becomes even simpler. Python’s tuple unpacking feature makes it possible to swap two tuples in a single, elegant statement.

To swap two tuples means to exchange their values so that the first tuple becomes equal to the second tuple's initial value, and the second tuple becomes equal to the first tuple's initial value.

2. Program Steps

1. Define two tuples with some initial values.

2. Swap the tuples using tuple unpacking.

3. Print the tuples after the swap to verify the swap operation.

3. Code Program

# Define two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Print original tuples
print("Original tuples:")
print("tuple1:", tuple1)
print("tuple2:", tuple2)

# Swap the tuples
tuple1, tuple2 = tuple2, tuple1

# Print swapped tuples
print("\nSwapped tuples:")
print("tuple1:", tuple1)
print("tuple2:", tuple2)

Output:

Original tuples:
tuple1: (1, 2, 3)
tuple2: (4, 5, 6)
Swapped tuples:
tuple1: (4, 5, 6)
tuple2: (1, 2, 3)

Explanation:

1. tuple1 and tuple2 are initialized with values (1, 2, 3) and (4, 5, 6), respectively.

2. The original tuples are printed showing the initial state before swapping.

3. The tuples are swapped using a single line of code: tuple1, tuple2 = tuple2, tuple1. This is possible because Python creates a temporary invisible tuple (tuple2, tuple1) and unpacks it immediately into tuple1 and tuple2.

4. The new state of the tuples is printed out, confirming the swap. tuple1 now has the values (4, 5, 6), and tuple2 has the values (1, 2, 3).

Comments