Example 1: python lambda key sort
>>> student_tuples = [
... ('john', 'A', 15),
... ('jane', 'B', 12),
... ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Example 2: sorted list python
sorted(iterable, key=None, reverse=False)
type(sorted(iterable, key=None, reverse=False)) = list
Example 3: python sort list in place
your_list.sort()
your_list = [42, 17, 23, 111]
your_list.sort()
print(your_list)
--> [17, 23, 42, 111]
your_list = ['42', '17', '23', '111']
your_list.sort(key=int)
print(your_list)
--> ['17', '23', '42', '111']
your_list =['cmd1','cmd10', 'cmd111', 'cmd50', 'cmd99']
your_list.sort(key=lambda x: int(x[3:]))
print(your_list)
--> ['cmd1', 'cmd10', 'cmd50', 'cmd99', 'cmd111']
your_list = [42, 17, 23, 111]
your_list_sorted = sorted(your_list)
print(your_list_sorted)
--> [17, 23, 42, 111]
Example 4: python sort comparator
sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
sorted(student_tuples, key=lambda student: student[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Example 5: pyhton built in sort
arr = [ 1, 3, 2]
arr.sort()
Example 6: python sort multiple keys
records.sort(
key = lambda l: (l[0], l[2])
)