Python List sort() Method

Example

Sort the list in alphabetical order:

cars = ['Porsche', 'BMW', 'Volvo']
cars.sort()

Run Instance

Definition and Usage

By default, the sort() method sorts the list in ascending order.

You can also let the function decide the sorting criteria.

Syntax

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

Parameter value

Parameter Description
reverse Optional. reverse=True will sort the list in descending order. The default is reverse=False.
key Optional. Specify a function to determine the sorting criteria.

More Examples

Example 1

Sort the list in descending order:

cars = ['Porsche', 'BMW', 'Volvo']
cars.sort(reverse=True)

Run Instance

Example 2

Sort the list by the length of the values:

Function to return the length of the value:
def myFunc(e):
  return len(e)
cars = ['Porsche', 'Audi', 'BMW', 'Volvo']
cars.sort(key=myFunc)

Run Instance

Example 3

Sort the list of dictionaries by the 'year' value:

Function to return the 'year' value:
def myFunc(e):
  return e['year']
cars = [
  {'car': 'Porsche', 'year': 1963},
  {'car': 'Audi', 'year': 2010},
  {'car': 'BMW', 'year': 2019},
  {'car': 'Volvo', 'year': 2013}

cars.sort(key=myFunc)

Run Instance

Example 4

Sort the list in descending order by the length of the values:

Function to return the length of the value:
def myFunc(e):
  return len(e)
cars = ['Porsche', 'Audi', 'BMW', 'Volvo']
cars.sort(reverse=True, key=myFunc)

Run Instance