- 40 Algorithms Every Programmer Should Know
- Imran Ahmad
- 85字
- 2025-04-04 12:59:10
Swapping Variables in Python
When implementing sorting and searching algorithms, we need to swap the values of two variables. In Python, there is a simple way to swap two variables, which is as follows:
var1 = 1
var2 = 2
var1,var2 = var2,var1
>>> print (var1,var2)
>>> 2 1
Let's see how it works:

This simple way of swapping values is used throughout the sorting and searching algorithms in this chapter.
Let's start by looking at the bubble sort algorithm in the next section.