How to sort a list in Python

Sort()

The list is automatically sorted in ascending order using the sort().

Doing a function to select sorting criteria is another option(s).

Syntax

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

Example

def myFunc(e):
return e['year']

cars = [
{'car': 'Peugeot', 'year': 2015},
{'car': 'Mitsubishi', 'year': 2010},
{'car': 'BMW', 'year': 2022},
{'car': 'Citroën', 'year': 2012}
]

cars.sort(key=myFunc)

[{'car': 'Mitsubishi', 'year': 2010}, {'car': 'Citroën', 'year': 2012}, {'car': 'Peugeot', 'year': 2015}, {'car': 'BMW', 'year': 2022}]