Elements can be easily replaced by connecting the element numbers with equals.
For example, if you want to swap the beginning and end of an array containing integers from 1 to 5, you can swap the values on the left and right and connect them with equals.
python
a = [1,2,3,4,5]
a[0], a[4] = a[4], a[0]
print(a)
#[5, 2, 1, 4, 5]
python
a = [1,2,3,4,5]
a[0], a[1], a[2] = a[4], a[4], 5
print(a)
#[5, 5, 5, 4, 5]
It can be used without giving a variable name.
python
a,b,c,d =1,2,3,4
a,c = c, a
print(a,b,c,d)
#3 2 1 4
If the value on the left side is other than one, an error will occur. When there is only one on the left side, a set value is entered.
python
a = [1,2,3,4,5]
a[0] = a[4], a[4], a[4]
print(a)
#[(5, 5, 5), 2, 3, 4, 5]
python
a = [1,2,3,4,5]
a[0], a[1] = a[4], a[4], a[4]
print(a)
#ValueError: too many values to unpack (expected 2)
Recommended Posts