Swapping the values of two variables in Python is actually a really simple task. Python makes it fairly easy to swap two values without a lot of bulky code or weird hacks. Check out how easy it is to swap two numbers with each other using the built in methods below:
x, y = 33, 81 print(x, y)
x, y = y, x print(y, x)
- Python Programming – Creation, Initialization and Accessing The Elements In A Tuple
- Python Programming – Structure Of A Python Program
- Python Programming – Numbers
The result of the first example would be 33, 81, while the results of the second example will have been swapped so that the results read 81, 33. This swapping can be achieved with any sort of variable and isn’t limited to just numbers, but can be used with strings too.