Python List sort() Method

Sorts the list in ascending order or optionally in descending order.

Syntax

Python
list.sort(reverse = False, key = None)

Parameters

ParameterDescription
reverse Optional. A boolean value that specifies whether to sort the list in reverse order (True) or the 'usual' order (False)
key Optional. A function that is used to compare items in the list for the purpose of sorting. This function should return a value for a given item. This is typically used where items in the list are classes or complex objects rather than simple values, and so this function may return a representative value for this object that allows it to be easily sorted

Example

Python
vehicles = [ 'Car', 'Truck', 'Motorbike' ]
vehicles.sort()

# Note we prefix with 'f' to output the list items
print(f'Vehicles in alphabetical order: {vehicles}')

vehicles = [ 'Car', 'Truck', 'Motorbike' ]
vehicles.sort(reverse = True)
print(f'Vehicles in reverse alphabetical order: {vehicles}')

Output

Vehicles in alphabetical order: ['Car', 'Motorbike', 'Truck']
Vehicles in reverse alphabetical order: ['Truck', 'Motorbike', 'Car']

Example

Python
vehicles = [
    { 'type' : 'Car',       'brand' : 'BMW' },
    { 'type' : 'Truck',     'brand' : 'Silverado' },
    { 'type' : 'Motorbike', 'brand' : 'Triumph' }
 ]

def vehicleType(item):
    return item['type'] # return the vehicle type

to_sort = vehicles.copy()
to_sort.sort(key = vehicleType)
print(f'Vehicles ordered by type: {to_sort}')


def vehicleBrand(item):
    return item['brand'] # return the vehicle brand

to_sort = vehicles.copy()
to_sort.sort(key = vehicleBrand)
print(f'Vehicles ordered by brand: {to_sort}')

Output

Vehicles ordered by type: [{'type': 'Car', 'brand': 'BMW'}, {'type': 'Motorbike',
 'brand': 'Triumph'}, {'type': 'Truck', 'brand': 'Silverado'}]
Vehicles ordered by brand: [{'type': 'Car', 'brand': 'BMW'}, {'type': 'Truck', 
'brand': 'Silverado'}, {'type': 'Motorbike', 'brand': 'Triumph'}]

Example

We can also simplify the syntax by using a lambda function

Python
types = [ 'Motorbike', 'Car', 'Truck' ]
types.sort(key = lambda item: len(item))
print(f'Types ordered by length: {types}')

Output

Types ordered by length: ['Car', 'Truck', 'Motorbike']