+ 1

Explain me this code! What is a[x] value?

a = [3,2,0,1] b = [1,0,3,2] b.sort(key=lambda x: a[x]) Print(b) #prints [2,3,1,0]

23rd Jan 2019, 8:04 AM
Aakash Gupta
Aakash Gupta - avatar
4 Answers
+ 6
From how I understand, b is the “key” and a is the list being changed. The first item in b is 1, and a[1] is 2. The second item is 0, and a[0] is 3. The third item is 3, and a[3] id 1. The last item is 2, and a[2] is 0. So then b now is [2, 3, 1, 0];
23rd Jan 2019, 8:47 AM
Rowsej
Rowsej - avatar
+ 2
What Rowsej said, but exactly the other way round. b is sorted, a is used as a key. b = [1, 0, 3, 2] For the first element (1), the key is a[1], which is 2. So the value 1 will have the index 2 in the sorted list: sorted b = [?, ?, 1, ?] For the second element (0), the key is a[0], which is 3. So the value 0 will have the index 3 in the sorted list: sorted b = [?, ?, 1, 0] For the third element (3), the key is a[3], which is 1. So the value 3 will have the index 1 in the sorted list: sorted b = [?, 3, 1, 0] For the fourth element (2), the key is a[2], which is 0. So the value 2 will have the index 0 in the sorted list: sorted b = [2, 3, 1, 0]
23rd Jan 2019, 10:08 AM
Anna
Anna - avatar
+ 2
Thank you Anna
23rd Jan 2019, 12:17 PM
Aakash Gupta
Aakash Gupta - avatar
+ 1
Thanks.. Rowsej
23rd Jan 2019, 9:25 AM
Aakash Gupta
Aakash Gupta - avatar