[Tutor] key parameter in sorted

Manprit Singh manpritsinghece at gmail.com
Mon Jun 29 08:35:01 EDT 2020


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 ?

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

Regards
Manprit Singh


More information about the Tutor mailing list