Python Tutorials · Python Lists

Sort Lists

Learn all about Sort Lists in this comprehensive tutorial.

5 min read beginner
  • List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
  • To sort descending, use the keyword argument reverse = True:
  • You can also customize your own function by using the keyword argument key = function.
  • By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:
  • What if you want to reverse the order of a list, regardless of the alphabet?

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

python
python

Sort Descending

To sort descending, use the keyword argument reverse = True:

python
python

Customize Sort Function

You can also customize your own function by using the keyword argument key = function.

The function will return a number that will be used to sort the list (the lowest number first):

python

Case Insensitive Sort

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:

python

Luckily we can use built-in functions as key functions when sorting a list.

So if you want a case-insensitive sort function, use str.lower as a key function:

python

Reverse Order

What if you want to reverse the order of a list, regardless of the alphabet?

The reverse() method reverses the current sorting order of the elements.

python

Module quiz

2 questions
1

Which of the following is true about Sort Lists?

2

What is the most common pitfall when working with Sort Lists?

Answer all questions to submit.