Swapping values in Python

Swapping elements such as arrays in Python can be expressed without using temporary variables. The bottom line is that you can use ** unpack **.

For example, suppose you have the following array.

list.c


int lst[] = [2, 7, 4, 9, 13, 6, 3];

I want to replace the elements of the array here. At this time, in the case of C language etc., a temporary variable must be prepared. For example, if you want to swap the 0th and 4th of the above array,

exchange.c


//An example of how to write
int tmp;
tmp = lst[4];
lst[0] = lst[4];
lst[0] = tmp;

However, in the case of Python, you can use unpack to write:

list.py


lst = [2, 7, 4, 9, 13, 6, 3];

exchange.py


lst[0], lst[4] = lst[4], lst[0]

From this point of view, Python is good because it can be written simply (^^)

Recommended Posts

Swapping values in Python
Transfer parameter values in Python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Python: Tips-Swap values
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
Read DXF in python
Daily AtCoder # 53 in Python
Use config.ini in Python
Daily AtCoder # 33 in Python
Solve ABC168D in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python