Home > OS >  Python - switching positions: list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i
Python - switching positions: list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i

Time:06-01

could anyone explain me, why is it not possible to swap list positions in my function for selection sort? This is what i wrote at first, but the function returns the same list as the input:

def selection_sort(list):
    for i in range(0, len(list)):
        minimum = list[i]
        for j in range(i   1, len(list)):
            if list[j] < minimum:
                minimum = list[j]
        list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i]
    return list

Then I tried to use a variable index = list.index(minimum) and suddenly it worked.

def selection_sort(list):
    for i in range(0, len(list)):
        minimum = list[i]
        for j in range(i   1, len(list)):
            if list[j] < minimum:
                minimum = list[j]
        index = list.index(minimum)
        list[i], list[index] = list[index], list[i]
    return list

Could anyone explain me the difference and why is it not corect the first solution? Thank you!

CodePudding user response:

The right hand side of the assignment (list[list.index(minimum)], list[i]) is computed first, then assigned to the tuple on the left list[i], list[list.index(minimum)].

I'm guessing the next part, but I assume list[i] is assigned to, then list[list.index(minimum)]. However, since you've already assigned to list[i] you've already modified the list before finding list.index(minimum) a second time. Since you're not searching in identical lists, the indexes may be different.

Your second attempt calculates the index once and uses the same value in both places.

As a side note, it is good practice to not name variables the same as a python builtin name. Your function takes a parameter called list so that "shadows" the builtin list function. You wouldn't be able to call that builtin inside your function because the name has been stolen. Better to call it my_list, array, or list_to_sort etc.

  • Related