Daily Grind 2: Python Sorting

I have only been recently getting into python – at first for fun on CodinGame, and then more recently for some side work (including the MailChimp integration). Something that I often find necessary for the various CodinGame puzzles and contests is sorting lists and dictionaries. I often have to look up the correct ways to sort, especially when my the lists or definitions contain more complicated objects. I figured this would be a good opportunity to share some of what I’ve found.

Sorting Lists

a = [3,5,1,2,4]
a.sort()
print(a) #[1,2,3,4,5]

This is the most basic example. Calling .sort on a list will update the list itself, and sort in a ascending order. To sort descending, simply pass reverse=True, like so:

a = [3,5,1,2,4]
a.sort(reverse=True)
print(a) #[5,4,3,2,1]

The other option is to use the sorted method, which accepts any iterable. The sorted method will not alter the list itself, but will instead return the resulting iterable.

Notice that the result of the sort is still a list. Sorting dictionaries results in lists – since the order of the dictionary itself does not matter. Dictionaries are referenced directly by unordered keys, so if you want to get a sorted version of the dictionary, the result will be a list.

When it comes to sorting objects, most of the concepts are the same. One key difference is that you have to specify which property on the object you want to sort the list by. The example above shows the results when sorting the list by prop1 vs prop2.