Ad
  • Default User Avatar

    When you pass a function, f, to the key parameter, the elements of the iterable are sorted according to the returned value of that function and not their own value. Basically, the function receives one argument (each element) and maps it to a given value which is used only for establishing the order between elements. This means that for instance e1>e2 if f[e1]>f[e2].

    In this case, the returned value of the function (x >= k) is a boolean, and therefore the function maps the elements either to 0 (False), if x<k , or 1 (True) if x>=k. All elements less than k (value 0) will be placed before the elements greater or equal to k (value 1) since 0 < 1.

    Note that the original order in the list is still preserved for elements mapped to the same value because they are “equivalent under the function”, and therefore don’t switch position with each other when compared.