TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.8K subscribers
Post #9219 1.16K
A bit of Python basics. Day 6 - Exchanging variable values

In Python, you can swap variables after they have already been assigned objects. Below, we first assign 20 to the variable x and 30 to the variable y, and then swap them: x becomes 30, and y becomes 20. This method is called tuple packing/unpacking.

x, y = 20, 30
x, y = y, x

print('x is: ', x)
print('y is: ', y)


x is 30
y is 20


You can also use the XOR (exclusive or) operator to swap variables. This is a three-step method. In the example below, we swap the values of x and y.

x = 20
y = 30

# step one
x ^= y
# step two
y ^= x
# step three
x ^= y

print(f'x is: {x}')
print(f'y is: {y}')


x is: 30
y is: 20


You can also use arithmetic operations (addition and subtraction) to swap variables without a temporary variable. However, this method is recommended for swapping numeric data types. Here's an example:

# Use arithmetic operations
x = 5
y = 10

x = x + y
y = x - y
x = x - y

print("After swapping:")
print("x =", x)
print("y =", y)


After swapping:
x = 10
y = 5


As a result of these arithmetic operations, the values of x and y have actually been swapped. After the swap, x contains the original value of y (10), and y contains the original value of x (5).

This method of swapping variables without a temporary variable is based on the fact that when you add or subtract the value of one variable from another, you can effectively swap their values without the need for additional storage.

👉 https://t.me/DataScience4
  • ❤ 5
More from @pythonre
  1. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  2. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  3. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  4. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
  5. Oct 6, 2026Post #9851
  6. Oct 6, 2026Python For Beginners Course In-Depth Python: A Comprehensive Introduction to Fundamental P…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →