Take a look at this Example, you will understand:
Example 1:
a = input()
a = sorted(a, key = lambda x:(len(x),x))
print(a)
input: ["tim", "bob", "anna", "steve", "john","aaaa"]
output: ['bob', 'tim', 'aaaa', 'anna', 'john', 'steve']
input: ["tim", "bob", "anna", "steve", "john","aaaaa"]
output: ['bob', 'tim', 'anna', 'john', 'aaaaa', 'steve']
Example 2 (advanced):
a = ["tim", "bob", "anna", "steve", "john","aaaaa","zzza"]
a = sorted(a, key = lambda x:(x[-1],len(x),x))
print(a)
output: ['anna', 'zzza', 'aaaaa', 'bob', 'steve', 'tim', 'john']
Example 3 (advanced):
a = [[1,4],[2,5],[3,1],[1,6],[3,8],[4,9],[0,3],[2,6],[9,5]]
a = sorted(a, key = lambda x:(-x[1],x[0]))
print(a)
output: [[4, 9], [3, 8], [1, 6], [2, 6], [2, 5], [9, 5], [1, 4], [0, 3], [3, 1]]
Conclusion:
key = lambda x:(p1,p2,p3,p4,...,pn)
,
x
is one element at a time from the stream of input.
p1,p2,p3...pn
being properties based on which the stream of elements needs to be sorted.
based on priority order of p1>p2>p3>...>pn
.
We can also add reverse=True, after the sorting condition, to sort the elements in reverse order.