Swap Two Variables
Swap the values of two variables using a temporary variable and Python’s tuple unpacking.
BeginnerTopic: Basic Python Programs
What You'll Learn
- Swapping values using a temporary variable
- Using Python tuple unpacking for swapping
- Understanding multiple assignment in Python
Python Swap Two Variables Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Swapping using a temporary variable
a = 5
b = 10
temp = a
a = b
b = temp
print("After swapping (using temp): a =", a, "b =", b)
# Swapping using Python tuple unpacking
x = 5
y = 10
x, y = y, x
print("After swapping (tuple unpacking): x =", x, "y =", y)Output
After swapping (using temp): a = 10 b = 5 After swapping (tuple unpacking): x = 10 y = 5
Step-by-Step Breakdown
- 1Initialize two variables with sample values.
- 2Swap them using a temporary variable and print the result.
- 3Reinitialize two variables.
- 4Swap them using tuple unpacking.
- 5Print the swapped values again.
Understanding Swap Two Variables
This program demonstrates two ways to swap the values of variables in Python.
1.
Using a temporary variable
:
•Store
a in temp.•Assign
b to a.•Assign
temp to b.2.
Using tuple unpacking (Pythonic way)
:
•
x, y = y, x swaps the values in a single line.Python’s multiple-assignment feature makes swapping very concise and readable.
Let us now understand every line and the components of the above program.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.