Does anyone know what is the exact idea of the line nestedlist.sort(key= lambda x: x[1]) ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Does anyone know what is the exact idea of the line nestedlist.sort(key= lambda x: x[1]) ?

nestedlist= [["Harry",37.21],["Berry",37.21],["Tina",37.2],["Akriti",41],["Harsh",39]] nestedlist.sort() new_list=[] nestedlist.sort(key= lambda x: x[1]) print(nestedlist) for sublist in nestedlist: print(sublist) print(sublist[1]) if sublist[1]==nestedlist[1][1]: new_list.append(sublist[0]) print(new_list) for x in new_list: print(x)

6th Dec 2019, 5:15 PM
Esteban Rueda
Esteban Rueda - avatar
2 Answers
+ 1
i think it said "sort nestedlist by using index 1 from each lists inside it" or simply but less accurate "sort index 1 from the lists inside nestedlist, but take the list it resides in when sorted" so its sorting the "inside" list, by comparing its 2nd element.
6th Dec 2019, 5:33 PM
Taste
Taste - avatar
0
When you sort items in a list, then each one is compared according to how that type usually is compared. When comparing two sequences, like str, tuple and lists, the elements are compared one by one, until one of the elements is smaller. With any of the sorts, and also for max or min, if you don't like the standard behaviour of the types when they're compared, you can give a key function, that says what's supposed to be compared instead. In this case, giving that lambda function, you tell the sort method: 'Don't compare each element of both lists - just look at index 1!
6th Dec 2019, 7:25 PM
HonFu
HonFu - avatar