Python Forum
understanding sorted key parameter - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: understanding sorted key parameter (/thread-11893.html)



understanding sorted key parameter - amirt - Jul-30-2018

Can someone explain what is happening in the following sorting action:

I have a list:
L = ['breathe', '_', 'd', '+', 'a', 'bear']
If i sort it with the key parameter checking if there is an item in the list:

sorted(l,key=lambda x: x=="a")
"a" is replaced as the last item in the sorted list:

['breathe', '_', 'd', '+', 'bear', 'a']
What is happening?


RE: understanding sorted key parameter - volcano63 - Jul-30-2018

Output of key function defines which element is "larger". x == 'a' produces False for each element but 'a', and since

False < True
and default sort order is ascending, element 'a' becomes the "largest" element


RE: understanding sorted key parameter - amirt - Jul-30-2018

Great, many thanks!