Let's discuss a few features of sorting in python. This is something we will treat as a "black box" for now; that is, we'll just use it as a tool given to us without understanding the implementation details. But later we will go over the details later of how these algorithms work.

First, let's create a list of 50 random numbers between 0 and 99 using numpy

Sorting them in python is as simple as saying

So what's the big deal? Well, things can get a little fancier if we are sorting a list of objects. For example, suppose we had an object which encapsulated both a string and a number. To keep things simple, we'll make each name a 3-character string with only the characters "a" "b" and "c". I'll go ahead and make a random list of such objects now

For example, here are the first two elements

But what happens when we try to sort these?

Uh oh! The issue is, we haven't defined how to sort objects of type "NumStr". What we have to do is define a special function to say how to sort. This function should return something about the object which is comparable (e.g. ints by value or strings in alphabetical order). Let's define two functions for our object: one that returns the name and one that returns the number

Now, we can pass along these functions as parameters to the sorted function. For example, let's sort them by number and print out the first 10.

Let's take this result and now sort it by name

Sharp eyes will notice that within the ties, each chunk is sorted by number (e.g. for everything with a name aaa, they come out 347, 593, 606, and 964). This is because python's sorted uses what's known as a stable sort. We won't immediately need this, but it's a good thing to know and keep in our back pocket

One more thing to mention is that the methods we passed to sorted were incredibly simple. There's actually a short hand for these types of one line method definitions in python known as an anonymous function. Below is how you could use this to sort by number again