logo

How to Swap the Values of Two Variables in Python 📂Programing

How to Swap the Values of Two Variables in Python

Code

Swapping variables is commonly implemented by creating a temporary variable and moving values accordingly. However, as someone dealing with multiple programming languages, it’s hard to be sure if this method works well in Python due to its characteristic of exchanging pointers when binding variables. Moreover, writing a function to swap variables for each case can be tedious. Let’s solve this easily with Python’s syntax itself.

x = 3
y = 5
print("x :%d y : %d" % (x,y))
x, y = y, x
print("x :%d y : %d" % (x,y))