by: Cobena Isaac

How to Swap Variable Values in Python

How to Swap Variable Values in Python

In Python, you can swap the values of two variables in a single line without using a temporary variable.

Example:

Swapping Two Variables

a = 5
b = 10

# Swap values in one line
a, b = b, a

print(a)  # Output: 10
print(b)  # Output: 5

For this Example

  1. Python first evaluates (b, a) and creates a temporary tuple (10, 5)
  2. Python then unpacks this tuple, assigning the values to a and b in order

After the operation:

  • a becomes 10
  • b becomes 5

The result is efficient value exchange between the two variables.

Real-Life Analogy

Imagine you and a friend each holding a cup—one with coffee, one with tea. Instead of finding a third cup to facilitate the swap, you simply exchange cups directly. That’s exactly what Python does during variable swapping!


Try It Yourself

  1. Swap Different Data Types:
x = "Apple"
y = "Banana"

x, y = y, x

print(x)  # Output: Banana
print(y)  # Output: Apple
  1. Swap Three Variables:
a, b, c = 1, 2, 3
a, b, c = c, a, b

print(a, b, c)  # Output: 3 1 2

Tip: This technique works with any data type and any number of variables—Python handles the complex rearrangement behind the scenes!

Hope this tutorial was helpful. Read our other tutorials to learn more.

Now that you’ve mastered variable swapping, continue to How to Assign Values from Collections in Python to learn how to extract multiple values from lists, tuples, and other data structures.