Swap values in a list or values of variables in Python
In Python, you can easily swap values without
temp (temporary variable).
It is possible to swap values of variables and to swap values (elements) in a list.
Swap values of variables
To swap values of variables, write as follows:
a = 1 b = 2 a, b = b, a print('a = ', a) print('b = ', b) # a = 2 # b = 1
You don't have to set up temporary variables like
Similarly, you can write assignments of values to multiple variables in one line.
- Related: Multiple assignment in Python: Assign multiple values or the same value to multiple variables
a, b = 100, 200 print('a = ', a) print('b = ', b) # a = 100 # b = 200
Not only swap of two values but also three or more is possible.
a, b, c, d = 0, 1, 2, 3 a, b, c, d = c, d, a, b print('a = ', a) print('b = ', b) print('c = ', c) print('d = ', d) # a = 2 # b = 3 # c = 0 # d = 1
Swap values (elements) in a list
The elements of the list can also be replaced. The order of the elements of the list is rearranged.
l = [0, 1, 2, 3, 4] l, l = l, l print(l) # [3, 1, 2, 0, 4]
To sort all elements in ascending or descending order, use the built-in function
sorted() or the list method
print(sorted(l)) # [0, 1, 2, 3, 4] print(sorted(l, reverse=True)) # [4, 3, 2, 1, 0]