+ 1

How does this code works ?

I ran this code many times but I couldn't get it. my_list = ['car','plane','train','bike','rocket'] new_list = sorted(my_list, key = lambda x: x[-2]) print(new_list) Answer is ['car','rocket','train','bike','plane']

5th Feb 2020, 1:39 PM
Rajan K
Rajan K - avatar
2 Answers
+ 5
Normally, when you sort strings, they are compared lexically, letter by letter, about what you'd do in a dictionary. Now the added key function means: 'Instead of what you usually compare, compare what this function returns.' The lambda function returns the letter at index -2 (second before last letter), so only that is gonna get compared. Now look at the second last letter of each word in the final list: a, e, i, k, n Perfectly sorted.
5th Feb 2020, 2:13 PM
HonFu
HonFu - avatar
+ 2
key parameter takes a function, which every elements would pass to. Then it sorts the return values. In this case, the lambda returns the second last character of a string since you pass a list of strings. car -> a rocket -> e train -> i bike -> k plane -> n It's Alphabetical.
5th Feb 2020, 2:20 PM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar