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

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
=External=
* https://docs.python.org/3/howto/sorting.html
* https://www.geeksforgeeks.org/sorted-function-python/
* https://www.geeksforgeeks.org/sorted-function-python/
=Internal=
=Internal=
* [[Python Language Functions#sorted|Python Functions]]
* [[Python Language Functions#sorted|Python Functions]]
Line 7: Line 9:


Also see: {{Internal|Python_Language_List#Sort|List | Sort}}
Also see: {{Internal|Python_Language_List#Sort|List | Sort}}
=Comparing Elements=
==Key Function==
{{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.
<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>

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