howtouselinux

10 Ways to Sort List in Python

Table of Contents

Lists are Python’s most flexible ordered collection object type. Unlike strings, lists can contain any sort of object: numbers, strings, and even other lists.  Lists may be changed in place by assignment to offsets and slices, list method calls, deletion statements, and more—they are mutable objects.

Python List Sort method

The best way to sort a list in Python is using the sort method. The sort() function takes a list as an argument. It returns a new list that is sorted in ascending order by default. You can also specify the sorting method you want to use. The available sorting methods are:

  • AscendingOrder: This will sort the list in ascending order.
  • ReverseOrder: This will sort the list in reverse order.
  • AlphabeticalOrder: This will sort the list alphabetically.

 

The sort() method sorts the list ascending by default. we can also make a function to decide the sorting criteria(s).

Syntax
list.sort(reverse=True|False, key=myFunc)

  • reverse Optional. reverse=True will sort the list descending. Default is reverse=False
  • key Optional. A function to specify the sorting criteria(s)

 

Understanding sorting algorithm in Python

The sort() method uses ASCII-betical sorting (a general term meaning sorted by ordinal number) rather than alphabetical sorting. The American Standard Code for Information Interchange (ASCII, pronounced “ask-ee”) is a mapping between numeric codes (called code points or ordinals) and text characters.

In the ASCII system, A is represented by code point 65, B by 66, and so on, up to Z by 90. The lowercase a is represented by code point 97, b by 98, and so on, up to z by 122. When sorting by ASCII, uppercase Z (code point 90) comes before lowercase a (code point 97).

So, we will notice that sort() has some odd sorting behavior that puts a capital Z before a lowercase a in the following example.

>>> letters = [‘z’, ‘A’, ‘a’, ‘Z’]
>>> letters.sort()
>>> letters
[‘A’, ‘Z’, ‘a’, ‘z’]

 

If we want to make an alphabetical sort, pass the str.lower method to the key parameter. This sorts the list as if the values had the lower() string method called on them:

>>> letters = [‘z’, ‘A’, ‘a’, ‘Z’]
>>> letters.sort(key=str.lower)
>>> letters
[‘A’, ‘a’, ‘z’, ‘Z’]

Sort numeric list in Python

If the items in the list are numeric, they’re sorted by default in ascending numeric order.

>>> numbers = [2, 1, 4.0, 3]
>>> numbers.sort()
>>> numbers
[1, 2, 3, 4.0]

Sort List Permanently with the Python sort() Method

Python’s sort() method makes it relatively easy to sort a list. sort orders a list in place; it uses Python standard comparison tests and by default sorts in ascending order.

Imagine we have a list of cars and want to change the order of the list to store them alphabetically. To keep the task simple, let’s assume that all the values in the list are lowercase.

cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort()
print(cars)

[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]

cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort(reverse=True)
print(cars)

[‘toyota’, ‘subaru’, ‘bmw’, ‘audi’]

 

Sort List Temporarily with the Python sorted() Function

To maintain the original order of a list but present it in a sorted order, we can use the sorted() function. The sorted() function lets us display our list in a particular order but doesn’t affect the actual order of the list.

Let’s try this function on the list of cars.

cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(“Here is the original list:”)
print(cars)
print(“Here is the sorted list:”)
print(sorted(cars))
print(“Here is the original list again:”)
print(cars)

Here is the original list:
[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
Here is the sorted list:
[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]
Here is the original list again:
[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

Difference with sort and sorted

  • The list method sort() sorts the list itself, in place.
  • The general function sorted() returns a sorted copy of the list.

 

Sort List with key parameter in Python

we can modify sort behavior by passing in keyword arguments— a special “name=value” syntax in function calls. The value passed to that parameter must be a function that takes a single argument. The function will be invoked once per element, and the function’s return value will be used to sort the values.

Thus, we can sort elements of a list by this.

mylist = [‘abcd’, ‘efg’, ‘hi’, ‘j’]
mylist = sorted(mylist, key=len)

After executing this code, mylist will now be sorted in increasing order of length, because the built-in len function will be applied to each element before it’s compared with others.

[‘j’, ‘hi’, ‘efg’, ‘abcd’]

Sort List with reverse parameter in Python

>>> L = [‘abc’, ‘ABD’, ‘aBe’]
>>> sorted(L, key=str.lower, reverse=True) # Sorting built-in
[‘aBe’, ‘ABD’, ‘abc’]
>>> L = [‘abc’, ‘ABD’, ‘aBe’]
>>> sorted([x.lower() for x in L], reverse=True)
[‘abe’, ‘abd’, ‘abc’]

Sort List with function in Python

We can create our own function as sorting parameter.

Sort a list of dictionaries based on the “year” value of the dictionaries:

# A function that returns the ‘year’ value:
def myFunc(e):
return e[‘year’]
cars = [
{‘car’: ‘Ford’, ‘year’: 2005},
{‘car’: ‘Mitsubishi’, ‘year’: 2000},
{‘car’: ‘BMW’, ‘year’: 2019},
{‘car’: ‘VW’, ‘year’: 2011}
]
cars.sort(key=myFunc)

David Cao
David Cao

Hey there! I am David, a Cloud & DevOps Enthusiast and 18 years of experience as a Linux engineer. I work with AWS, Git & GitHub, Linux, Python, Ansible, and Bash. I am a technical blogger and a Software Engineer, enjoy sharing my learning and contributing to open-source.