Sorting Algorithms in Python

The sort() method is one of the ways you can sort a list in Python.

When using sort(), you sort a list in-place. This means that the original list is directly modified. Specifially, the original order of elements is altered.

The general syntax for the sort() method looks like this:

list_name.sort(reverse=..., key=... )

Let’s break it down:

  • list_name is the name of the list you're working with.
  • sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order.
  • sort() accepts two optional parameters.
  • reverse is the first optional parameter. It specifies whether the list will be sorted in ascending or descending order. It takes a Boolean value, meaning the value is either True or False. The default value is False, meaning the list is sorted in ascending order. Setting it to True sorts the list backwards, in desceding order.
  • key is the second optional parameter. It takes a function or method which is used to specify any detailed sorting criteria you may have.

The sort() method returns None, which means there is no return value since it just modifies the original list. It does not return a new list.

How to Sort List Items in Ascending Order Using the sort() Method

As mentioned earlier, by default, sort() sorts list items in ascending order.

Ascending (or increasing) order means that items are arranged from lowest to highest value.

The lowest value is on the left hand side and the highest value is on the right.

The general syntax to do this would look something similar to the following:

list_name.sort()

Let’s take a look at the following example which shows how to sort a list of whole numbers:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
#sort list in-place in ascending order
my_numbers.sort()
#print modified list
print(my_numbers)
#output#[3, 7, 8, 10, 11, 22, 33, 54, 100]

In the example above, numbers are sorted from smallest to largest.

You can also achieve the same when working with a list of strings:

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
#sort list in-place in alphabetical order
programming_languages.sort()
#print modified list
print(programming_languages)
#output#['C++', 'Go', 'Java', 'Python', 'Rust', 'Swift']

In this case, each string contained in the list was sorted in aplhabetical order.

As you saw in both examples, the original lists were directly changed.

How to Sort List Items in Descending Order Using the sort() Method

Descending (or decreasing) order is the opposite of ascending order — elements are arranged from highest to lowest value.

To sort list items in descending order, you need to use the optional reverse parameter with the sort() method, and set its value to True.

The general syntax to do this would look something like this:

list_name.sort(reverse=True)

Let’s reuse the same example from the previous section, but this time make it so the numbers are sorted in reverse order:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
#sort list in-place in descending order
my_numbers.sort(reverse=True)
#print modified list
print(my_numbers)
#output#[100, 54, 33, 22, 11, 10, 8, 7, 3]

Now all the numbers are arranged in reverse, with the largest value being on the left hand side and the smallest on the right.

You can also achieve the same when working with a list of strings.

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
#sort list in-place in reverse alphabetical order
programming_languages.sort(reverse=True)
#print modified list
print(programming_languages)
#output#['Swift', 'Rust', 'Python', 'Java', 'Go', 'C++']

List items are now arranged in reverse alphabetical order.

How to Sort List Items Using the key parameter with the sort() Method

You can use the key parameter to perform more customized sorting operations.

The value assigned to the key parameter needs to be something callable.

Callable is something that can be called, which means it can be invoked and referenced.

Some examples of callable objects are methods and functions.

This method or function assigned to key will be applied to all the elements in the list before any sorting occurs and will specify the logic for the sorting criteria.

Say you want to sort a list of strings based on their length.

For that, you assign the built-in len() function to the key parameter.

The len() function will count the length of each element stored in the list by counting the characters contained in that element.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]programming_languages.sort(key=len)print(programming_languages)#output#['Go', 'C++', 'Java', 'Rust', 'Swift', 'Python']

In the example above, strings are sorted in the default ascending order, but this time the sorting occurs based on their length.

The shortest string is on the left hand side and the longest on the right.

The key and reverse parameters can also be combined.

For example, you could sort the list items based on their length but in descending order.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]programming_languages.sort(key=len, reverse=True)print(programming_languages)#output#['Python', 'Swift', 'Java', 'Rust', 'C++', 'Go']

In the example above, strings go from longest to shortest.

Another thing to note is that you can create a custom sorting function of your own, to create more explicit sorting criteria.

For example, you can create a specific function and then sort the list according to the return value of that function.

Say you have a list of dictionaries with programming languages and the year each programming language was created.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

You can define a custom function that gets the value of a specific key from the dictionary.

💡 Keep in mind that a dictionary key and the key parameter that sort() accepts are two different things!

Specifically, the function will get and return the value of the year key in the list of dictionaries, which specifies the year when every language in the dictionary was created.

The return value will then apply as the sorting criteria for the list.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]
def get_year(element):
return element['year']

You can then sort according to the return value of the function you created earlier by assigning it to the key parameter and sort by the default ascending chronological order:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]
def get_year(element):
return element['year']
programming_languages.sort(key=get_year)print(programming_languages)

Output:

[{'language': 'C++', 'year': 1985}, {'language': 'Python', 'year': 1991}, {'language': 'Java', 'year': 1995}, {'language': 'Go', 'year': 2007}, {'language': 'Rust', 'year': 2010}, {'language': 'Swift', 'year': 2014}]

If you want to sort from the most recently created language to the oldest, or otherwise in descending order, you then use the reverse=True parameter:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]
def get_year(element):
return element['year']
programming_languages.sort(key=get_year, reverse=True)print(programming_languages)

Output:

[{'language': 'Swift', 'year': 2014}, {'language': 'Rust', 'year': 2010}, {'language': 'Go', 'year': 2007}, {'language': 'Java', 'year': 1995}, {'language': 'Python', 'year': 1991}, {'language': 'C++', 'year': 1985}]

To achieve exactly the same result you can create a lambda function.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rakesh Tripathi

Rakesh Tripathi

Consulting Engineer, Software Developer, Infra, Quora