Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips¶
You can use the built-in function
sortedto sort any iterable collection. It always a (new) list containing sorted data. Some mutable collections (e.g., list) have thee methodsortto sort elements in-place. BothsortedandCollection.sortaccept an argumentkeyfor specifying customized sorting criteria.
Sort a List¶
my_list = [7, 1, 2, 3.1415 * 1.5]
my_list[7, 1, 2, 4.71225]The function sorted returns a new sorted list.
sorted(my_list)[1, 2, 4.71225, 7]sorted with a customized sorting criteria.
import math
sorted(my_list, key=lambda x: math.sin(x))[4.71225, 7, 1, 2]my_list[7, 1, 2, 4.71225]The method list.sort sorts the list in place.
my_list.sort()
my_list[1, 2, 4.71225, 7]my_list.sort(key=lambda x: math.sin(x))
my_list[4.71225, 7, 1, 2]