Seize the opportunity to gain new skills and reshape your career!

Choose a free learning path and get valuable insights from first-rate courses

Code has been added to clipboard!

Making Python Sort Lists in Two Ways

Reading time 2 min
Published Feb 10, 2020
Updated Feb 10, 2020

TL;DR – depending on the method you choose, you can either sort an existing list in Python, or create a sorted one without changing the original.

How to sort a list in Python

The easiest way to make Python sort lists is using the sort function. It will modify the original list without creating a new one:

Example
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime']
pies.sort()

The system will sort numbers in an ascending order and strings in an alphabetical order. You can reverse this by including an optional argument reverse=True:

Example
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime']
pies.sort(reverse=True)

Creating a Python sorted list

In some cases, you might want to leave the original list untouched, but still need a sorted version of it. To achieve this, use the sorted method:

Example
pies = ['Pecan', 'Apple', 'Cherry', 'Keylime']
sorted_list = sorted(pies)

Just like with sort, you can use the reverse argument to make Python sort list in reverse order. You can also sort it according to a different criteria by using an optional key argument and defining a basis for sorting.

In the example below, we create a Python sorted list according to the length of the string:

Example
pies = ['Blackberries', 'Pecan', 'Lime', 'Cinammon']
sorted_list = sorted(pies, key=len)

Python sort list: useful tips

  • Sorting a list in alphabetical order can be performed wrong when you're dealing with both uppercase and lowercase letters, and the system treats them as if they were different in value. To work around this, use the key argument and define str.lower as the basis for sorting.
  • When working with tuples, the system will only see their first elements and sort accordingly. If you want your tupples sorted in a different manner, use the key argument to specify one.