Python has two built in sort functions: sort and sorted. The sort function will modify the list and sort it in-place. Sorted will take a list and return a new list sorted.
Why have two methods? Well, it is a somewhat more advance topic, but both have design advantages. Sometimes you want to sort in-plae to save memory. Othere times, you don't care about memory as much and want to return a new list to keep immutability. We will cover these ideas in the future if you haven't heard of them.
We begin with an example of the .sort
function. This is a method attached to the stardard list. Here is how we can sort a list of numbers.
arr = [5, 6, 1, 3]
arr.sort()
print(arr)
And if we wish to reverse the order (sort descending), we pass the reverse option.
arr = [5, 6, 1, 3]
arr.sort(reverse=True)
print(arr)
We can also get a little advanced. Let's say we want to sort a list of dictionaries by a property. We can pass a lambda
(think of it as passing a function) to the sort method's key parameter. Below says to sort the dictionaries by the str
key.
stats = [
{'hero': 'John Doe', 'str': 19, 'mp': 43},
{'hero': 'Robert Smith', 'str': 49, 'mp': 43},
{'hero': 'Dean Brown', 'str': 34, 'mp', 45},
]
stats.sort(key=lambda item: item['str'])
Now, for the sorted function, everything works the same way, but instead of calling a method on a list, we use a build in python function.
arr = [5, 6, 1, 3]
newArr = sorted(arr)
print(newArr)
arr = [5, 6, 1, 3]
newArr = sorted(arr, reverse=True)
print(newArr)
stats = [
{'hero': 'John Doe', 'str': 19, 'mp': 43},
{'hero': 'Robert Smith', 'str': 49, 'mp': 43},
{'hero': 'Dean Brown', 'str': 34, 'mp', 45},
]
newArr = sorted(users, key=lambda e: e['name'])
print(newArr)
The sort methods for python are very pthon. The ability to have a custom sort allows us to sort many different objects. Check out the docs for more info: https://docs.python.org/3/howto/sorting.html.