[Tutor] key parameter in sorted

Peter Otten __peter__ at web.de
Mon Jun 29 09:46:24 EDT 2020


Manprit Singh wrote:

> Sir,
> According to the python documentation,function sorted
> <https://docs.python.org/3/library/functions.html#sorted> have a *key*
> parameter to specify a function to be called on each  element prior to
> making comparisons.
> 
> consider a case if i am using python 3.6, and i have to remove duplicates
> from a list, while maintaining the order of the elements, i just need to
> know if my solution(which is given below )  is syntactically correct and
> efficient or not .
> The result i am getting is correct and have tested it  so many times .
> Reason for asking this question is, here i have passed  method of list
> data type (list.index) to the key parameter of sorted function . Can i
> pass a method to the key parameter of sorted function ?

You can pass any callable object as the key parameter.

> lx = [2, 5, 4, 6, 4, 2, 3, 6]
> sorted(set(lx), key=lx.index)

Your code is correct, but not efficient: you need up to len(lx) linear 
searches over the list just to calculate the key values.

An alternative may be to rely on dicts preserving insertion order 
(officially in 3.7, but implemented in 3.6):

>>> lx = [2, 5, 4, 6, 4, 2, 3, 6]
>>> list(dict.fromkeys(lx))
[2, 5, 4, 6, 3]




More information about the Tutor mailing list