note.nkmk.me

Swap values ​​in a list or values of variables in Python

Posted: 2019-06-24 / Tags: Python, List

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.

Sponsored Link

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 temp.

Similarly, you can write assignments of values to multiple variables in one line.

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[0], l[3] = l[3], l[0]

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 sort().

print(sorted(l))
# [0, 1, 2, 3, 4]

print(sorted(l, reverse=True))
# [4, 3, 2, 1, 0]
Sponsored Link
Share

Related Categories

Related Posts