Python Built-In Function sorted(): Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
Line 12: Line 12:
=Comparing Elements=
=Comparing Elements=
==Key Function==
==Key Function==
{{Externa|https://docs.python.org/3/howto/sorting.html#key-functions}}
{{External|https://docs.python.org/3/howto/sorting.html#key-functions}}


Both <code>sorted()</code> and <code>sort()</code> accept a <code>key</code> 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.
Both <code>sorted()</code> and <code>sort()</code> accept a <code>key</code> 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.

Latest revision as of 01:08, 11 February 2023

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