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

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 11: Line 11:


=Comparing Elements=
=Comparing Elements=
==Key Function==
{{Externa|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.
<syntaxhighlight lang='py'>
a = [Something("x"), Something("m"), Something("a")]
a.sort(key=lambda element: element._value)
for e in a:
    print(e)
</syntaxhighlight>
will display:
<syntaxhighlight lang='text'>
a
m
x
</syntaxhighlight>

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

Template:Externa

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