Python Forum

Full Version: understanding sorted key parameter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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
Great, many thanks!