Some of the most common value swapping methods are: For example C / C ++
swapSample.cpp
#include <iostream>
using namespace std;
int main(void){
//Initial setting
int x = 10;
int y = 25;
int tmp = 0;
cout << "x:"<< x << ", " << "y:"<< y << '\n';
//Exchange process here
tmp = x;
x = y;
y = tmp;
cout << "x:"<< x << ", " << "y:"<< y << '\n';
return 0;
}
//Output result:
// x:10, y:25
// x:25, y:10
In Python, this kind of swap processing is done as follows.
swapPython.py
x, y = 10, 25
print("x:{0}, y:{1}".format(x,y))
x,y = y, x #This alone swap!
print("x:{0}, y:{1}".format(x,y))
#Output result:
# x:10, y:25
# x:25, y:10
I often use this method conveniently, but this is what Python has. ** Tuple ** It is a function called.
This is different from the list
t = (1, 2, 3, 4, 5)
It is expressed as. Then
>>> t [ENTER]
> (1,2,3,4,5)
>>>
The value is stored as follows.
There are various ways to use it, but this time about swap.
The parentheses () can be omitted for tuples. The following expressions
swapPython.py
x, y = y, x #This alone swap!
Actually
swapPython.py
(x, y) = (y, x) #This alone swap!
This means that the tuple processing has been executed.
It was a little thing The process I'm always doing actually meant something like this You often notice that.
Recommended Posts