sorted()

Returns a new, sorted list built from the items of any collection.

Returns
A new, sorted list.
On this page

Example

#
Python
scores = [72, 95, 64, 88]
print(sorted(scores))
print(sorted(scores, reverse=True))
print(sorted(["Python", "CSS", "HTML"], key=len))
print(scores)
Resultsaved result, you can check it
[64, 72, 88, 95]
[95, 88, 72, 64]
['CSS', 'HTML', 'Python']
[72, 95, 64, 88]

Definition and usage

#

The sorted() function creates a new list with sorted items. The original collection stays unchanged, so it also works on tuples, sets, and strings.

The key parameter takes a function whose result decides the order, for example key=len sorts by length, and key=lambda s: s["points"] sorts by a dictionary field. The reverse=True parameter reverses the order.

Sorting in Python is stable: items with equal keys keep their relative order. That lets you sort by several criteria, by sorting first by the less important one.

Syntax

#
Syntax
sorted(iterable, key=None, reverse=False)

Parameters

#
  • iterable

    a collection

    The items to sort.
  • key

    function, optional

    A function that computes the sort key.
  • reverse

    bool, default False

    Descending order when True.

More examples

#
Sorting dictionaries
Python
students = [
    {"name": "Jack", "points": 90},
    {"name": "Emma", "points": 120},
    {"name": "Mia", "points": 90},
]

ranking = sorted(students, key=lambda s: (-s["points"], s["name"]))
print([s["name"] for s in ranking])
Resultsaved result, you can check it
['Emma', 'Jack', 'Mia']

Good practices

#
  • To sort by several criteria, return a tuple from key, e.g. (-points, name).
  • If you want to sort a list in place, without creating a new one, use the list.sort() method.

Related entries

#

Spotted a mistake or missing an example? Write to us.