Swap values in a list or values of variables in Python
In Python, you can easily swap values without temp
(temporary variable). You can swap values of variables as well as values (elements) in a list.
Swap values of variables
To swap values of variables, use the following syntax. In the example, an f-string is used.
a = 1
b = 2
a, b = b, a
print(f'{a = }')
print(f'{b = }')
# a = 2
# b = 1
source: swap_values.py
There's no need to set up temporary variables like temp
.
Similarly, you can assign values to multiple variables in a single line.
a, b = 100, 200
print(f'{a = }')
print(f'{b = }')
# a = 100
# b = 200
source: swap_values.py
Swapping is not limited to just two values; it is also possible to swap three or more values.
a, b, c, d = 0, 1, 2, 3
a, b, c, d = d, c, b, a
print(f'{a = }')
print(f'{b = }')
print(f'{c = }')
print(f'{d = }')
# a = 3
# b = 2
# c = 1
# d = 0
source: swap_values.py
Swap values (elements) in a list
The elements within a list can also be swapped. The order of the list elements is rearranged.
l = [0, 1, 2, 3, 4]
l[0], l[3] = l[3], l[0]
print(l)
# [3, 1, 2, 0, 4]
source: swap_values.py
To sort all elements in either ascending or descending order, use the built-in function sorted()
or the list method sort()
.
print(sorted(l))
# [0, 1, 2, 3, 4]
print(sorted(l, reverse=True))
# [4, 3, 2, 1, 0]
source: swap_values.py