python custom sort function code example

Example 1: python sort a list by a custom order

# Example usage:
list_to_sort = [('U', 23), ('R', 42), ('L', 17, 'D')]
custom_sort_order = ['R', 'D', 'L', 'U']
sorted(list_to_sort, key=lambda list_to_sort: custom_sort_order.index(list_to_sort[0]))
# Where 0 is the tuple index to use for sorting by custom order
--> [('R', 42), ('L', 17, 'D'), ('U', 23)]

Example 2: python sort

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Example 3: python sort list in place

# Basic syntax:
your_list.sort()

# Example usage:
your_list = [42, 17, 23, 111]
your_list.sort()
print(your_list)
--> [17, 23, 42, 111]

# If you have a list of numbers that are of type string, you can do the
# following to sort them numerically without first converting to type 
# int. E.g.:
your_list = ['42', '17', '23', '111']
your_list.sort(key=int)
print(your_list)
--> ['17', '23', '42', '111']

# If you want to sort a list of strings in place based on a number 
# that is consistently located at some position in the strings, use
# a lambda function. E.g.:
your_list =['cmd1','cmd10', 'cmd111', 'cmd50', 'cmd99']
your_list.sort(key=lambda x: int(x[3:]))
print(your_list)
--> ['cmd1', 'cmd10', 'cmd50', 'cmd99', 'cmd111']

# If you don't want to sort the list in place, used sorted. E.g.:
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])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Example 5: sorted python

var = sorted(old_var)