Python Forum
understanding sorted key parameter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
understanding sorted key parameter
#1
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?
Reply
#2
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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Great, many thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make elements return sorted? notsoexperienced 4 764 Sep-24-2020, 09:00 AM
Last Post: perfringo
  Why is my original list also sorted? Pedroski55 1 561 Jul-15-2020, 09:25 PM
Last Post: Yoriz
  Outputting Sorted Text files Help charlieroberrts 1 562 Jul-05-2020, 08:37 PM
Last Post: menator01
  sorted function example mystery sabaidii2 4 820 Feb-10-2020, 09:37 AM
Last Post: DeaD_EyE
  Byte array is sorted when sending via USB daviddlc68 1 1,031 Aug-16-2019, 10:11 AM
Last Post: wavic
  sorted object in list trois 2 1,097 Mar-04-2019, 09:12 AM
Last Post: trois
  sorted dictionary? HenryJ 2 1,532 Feb-05-2018, 08:36 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020