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