Home > front end >  Why does multiple variable assigment work for a quick sort algorithm but not for line by line assign
Why does multiple variable assigment work for a quick sort algorithm but not for line by line assign

Time:11-29

Hey guys this is a basic question and hopefully straight forwards.

Basically trying to understand why doing a multiple variable assignment for a quick sort implementation works, like follows:

if a_list[i] > a_list[i 1]:
    a_list[i], a_list[i 1] = a_list[i 1], a_list[i]

But not doing it line by line, like so:

if a_list[i] > a_list[i 1]:
    a_list[i] = a_list[i 1]
    a_list[i 1] = a_list[i]

Here is the full code if it helps:

def bubble_sort(a_list):
    last_ind = len(a_list) - 1
    flag = True
    
    while flag:
        flag = False
        for i in range(0, last_ind):
            if a_list[i] > a_list[i 1]:
                a_list[i], a_list[i 1] = a_list[i 1], a_list[i]
                flag = True
                
    return a_list
    
    
a_list = [5,8,2,1]
print(bubble_sort(a_list))

Thanks in advance.

CodePudding user response:

In the first implementation, behind the scenes python will create a tuple to store the values of both variables, then will change the values of the variables.

In the second implementation after the value of a_list[i] is changed, the previous value is lost, so there is no way to set a_list[i 1] to the correct value.

CodePudding user response:

Say a, b= 1, 2. Essentially it does tuple unpacking such that the values on the left (tuple) get assigned the value of the corresponding element on the right side (tuple).

So e.g. the above exame implies (a, b) = (1, 2) which in turn implies a=1 and b=2

Now assume that a=5 and `b=10'

a = 5
b = 10

# Right method
a, b = b, a    # same as saying (a, b) = (10, 5) and thus assigning a = 10 and b = 5

# Wrong method
a = b        # a is now assigned 10
b = a        # a is 10 from the previous line, and b is now assigned 10

I wouldnt say that the first method is instantaneous and the second is manual, but rather they do two different things. One of them is unpacking a tuple of values (which happened to be stored in variables) into a tuple of variables while the other is just i guess errored variable assignment.

One way to make the second method work would be

c = a   # new variable stores value of a
a = b   # a is reassigned to the value of b
b = c   # b is now reassigned to the original value of a (which was previously stored in c)

CodePudding user response:

The example

a_list[i] = a_list[i 1]
a_list[i 1] = a_list[i]

will modify the value at index i in a_list, then set index i 1 to that modified value. You can think of the multiple assignment syntax as Python doing both assignments at the same time, so one assignment wouldn't affect the other.

  • Related