+6

# Sort list using key and lambda

Could someone explain the output of the following please: a = [3, 2, 0, 1] b = [1, 0, 3, 2] b.sort(key = lambda x: a[x]) print(b) Why the result is [2, 3, 1, 0] ? Thanks

+5

Sorting using ' b.sort(key = lambda x: a[x])' means using values of a[b[i]] instead of b[i] to compare the elements. So the result is [2, 3, 1, 0] because: a[b] <= a[b] <= a[b] <= a[b] as 0 <= 1 <= 2 <= 3

+22

Hey Ingrid Horatius, I ll try to explain what's going on. # 1. iteration a[x] = 3 so b = 2 # 2. iteration a[x] = 2 so b = 3 # 3. iteration a[x] = 0 so b = 1 # 4. iteration a[x] = 1 so b = 0

+6

My understanding is, what the key parameter does is it assigns a value to each element of the sortable list b. This value is then used to establish the order. In the lambda function we use a custom function to establish these "rank" values, using the elements of the list a. So the result of lambda x: a[x] b=1 gets the rank a=2 b=0 gets the rank a=3 b=3 gets the rank a=1 b=2 gets the rank a=0 So the value 2 has the lowest rank (0) etc, hence the final order [2,3,1,0] Check also this article that has an excellent explanations, also on what happens if the rank values are equal. https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda

+2