The lambda returns a tuple for each value in the list. These tuples are then used to indicate the sort order. Therefore, instead of comparing '234' with '5' , the sorting algorithm is proposed to compare (3, '234') and (1, '5') .
Python sorts the tuples lexicographically , that is, first comparing the first elements of two tuples, then if they match, moving to compare the second elements, etc., until there are no elements that can be compared.
Since the tuple contains both the length and the string, for strings of equal length, the strings are sorted as follows according to their actual value. This puts longer lines at the end, shorter lines in front and inside each group of equal length lines are sorted by their value.
Looking again at your input example, for '234' and '5' , the resulting tuples (3, '234') and (1, '5') have unequal first elements, so (1, '5') sorted to (3, '234') . But for '5' and '2' resulting tuples (1, '5') and (1, '2') (both have a length of 1 character), and the first elements of these tuples are equal. Therefore, they are sorted by the second element, placing '2' to '5' .
Without such switches (so the keys are equal), Python leaves the relative order intact. For the first example, the sort key is simply len(x) , and since '5' and '2' are the same length and there is nothing to compare them, Python puts them in the output in the same relative order, '5' to '2' .