Python Built-In Function sorted()

From NovaOrdis Knowledge Base
Revision as of 01:08, 11 February 2023 by Ovidiu (talk | contribs) (→‎Key Function)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

External

Internal

Overview

Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence.

Also see:

List | Sort

Comparing Elements

Key Function

https://docs.python.org/3/howto/sorting.html#key-functions

Both sorted() and sort() accept a key argument which takes a function. The function is then invoked on each iterable to be sorted, and it is supposed to return a key to be used when sorting.

a = [Something("x"), Something("m"), Something("a")]
a.sort(key=lambda element: element._value)
for e in a:
    print(e)

will display:

a
m
x