I\'m going through the tutorial intro for Python and I\'m stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.
pairs = [(1, \'
Sometimes when starting to work with lambda
, it's easier to write out the function explicitly. Your lambda function is equivalent to:
def sort_key(pair):
return pair[1]
If we want to be more verbose, we can unpack pair to make it even more obvious:
def sort_key(pair):
int_value, string_value = pair
return string_value
Because list.sort
orders the items based on the return value of the key
function (if present), now we see that it is sorting the tuples by their string value. Since strings sort lexicographically, "four"
comes before "one"
(think alphabetical order).