Python Built-in Methods – Python List sort() Method

Python List sort() Method

Sorts the items of the list


Use sort() method to sort the items of the list.

You can optionally specify parameters for sort customization like sorting order and sorting criteria.



Parameter Condition Description
key Optional A function to specify the sorting criteria.
Default value is None.
reverse Optional Settting it to True sorts the list in reverse order.
Default value is False.

Please note that both the arguments must be specified as keyword arguments.

Sort List

sort() method sorts the list of strings alphabetically and the list of numbers numerically.

# Sort the list of strings
L = ['red', 'green', 'blue', 'orange']
# Prints ['blue', 'green', 'orange', 'red']
# Sort the list of numbers
L = [42, 99, 1, 12]
# Prints [1, 12, 42, 99]

However, you cannot sort lists that have both numbers and strings in them, since Python doesn’t know how to compare these values.

L = ['red', 'blue', 1, 12, 'orange',42, 'green', 99]
# Triggers TypeError: '<' not supported between instances of 'int' and 'str'

Sort List in Reverse Order

You can also sort the list in reverse order by setting reverse to TRUE.

L = ['red', 'green', 'blue', 'orange']
# Prints ['red', 'orange', 'green', 'blue']

Sort with Key

Use key parameter for more complex custom sorting. A key parameter specifies a function to be executed on each list item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) sorts the strings by length, from shortest to longest.

L = ['red', 'green', 'blue', 'orange']
# Prints ['red', 'blue', 'green', 'orange']

A function to be used as key must take a single value and return single value.

Sort with Custom Function

You can also pass in your own custom function myFunc as the key function.

# Sort a list of tuples based on the age of students
def myFunc(e):
  return e[1]	# return age

L = [('Bob', 30),
     ('Sam', 35),
     ('Max', 25)]
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
# Sort a list of dictionaries based on the age of students
def myFunc(e):
    return e['age']		# return age

L = [{'name': 'Bob', 'age': 30},
     {'name': 'Sam', 'age': 35},
     {'name': 'Max', 'age': 25}]
# [{'age': 25, 'name': 'Max'}, {'age': 30, 'name': 'Bob'}, {'age': 35, 'name': 'Sam'}]

Case-insensitive Sorting

By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.

# Case-sensitive sorting
L = ['Red', 'blue', 'Green', 'orange']
# Prints ['Green', 'Red', 'blue', 'orange']

If you want to sort the values in regular alphabetical order, set key to str.lower

# Case-insensitive sorting
L = ['Red', 'blue', 'Green', 'orange']
# Prints ['blue', 'Green', 'orange', 'Red']

This causes the sort() function to treat all the list items as if they were lowercase without actually changing the values in the list.

sort() vs sorted()

The sort() method doesn’t return anything, it modifies the original list (i.e. sorts in-place). If you don’t want to modify the original list, use sorted() function. It returns a sorted copy of the list.

# Get a sorted copy of the list with sorted()
L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
# Prints ['blue', 'green', 'orange', 'red']
# Iterate through a sorted list without changing the original
L = ['red', 'green', 'blue', 'orange']
for x in sorted(L):
# Prints blue green orange red

Another difference is that the sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable like tuple, dictionary etc. Also, the sort() method doesn’t need to create a new list, so it’s faster between the two.


Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.