Search code examples
pythonpython-3.xlistsortingswap

Am I swapping elements from a list correctly?


Info: I am a HS student who is learning how to code and I don't know of anyone who can check my logic for me, so I am using the kind souls of Stack Overflow to help check my thinking.

Actual question: I am learning about sorting, and I want to know if I actually understand what is going on during the swapping proccess.

my_list = [1, 2]

my_list[0], my_list[1] = my_list[1], my_list[0]

print(my_list)

Output:
[2, 1]

Here is what I think this does. I set what ever is in the 0th position of my_list = to whatever is in the 1st position of my_list, which is basically saying, "Hey, trade values!". Then I do the same thing with the first position of my_list, accept I set it = what ever is in the 0th position of my list. What I think this does, and correct me if I'm wrong, is that is sets the value of the 0th position = to the value of the 1st position, and it sets the value of the 1st position = to the value of the 0th position. This in turn changes the values of the list elements, making it look as though they have traded places. Is this correct or am I overthinking this? I know this sounds like basic assignment, but I want to make sure I fully understand this concept of swapping.


Solution

  • Answer to the actual question. What's going on during swapping is the following.

    1. Python computes what is on the right side from = operator. That is Python gets two values my_list[1] and my_list[0] which are 2 and 1. Then Python packs the values into tuple (2, 1).

    2. Python assigns the tuple (2, 1) to the variable on the left side from = operator.

    3. There are 2 variables on the left side from = operator AND tuple (2, 1) has exactly 2 items. So Python unpacks the tuple then assigns 2 to the first variable (which happened to be the first element of the list my_list) and assigns 1 to the second variable.

    So swapping values is obtained through packing and upacking hidden from user.