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
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 10,634 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  Failing to print sorted files tester_V 4 1,188 Nov-12-2022, 06:49 PM
Last Post: tester_V
  set and sorted, not working how expected! wtr 2 1,254 Jan-07-2022, 04:53 PM
Last Post: bowlofred
  How to make elements return sorted? notsoexperienced 4 3,164 Sep-24-2020, 09:00 AM
Last Post: perfringo
  Why is my original list also sorted? Pedroski55 1 1,580 Jul-15-2020, 09:25 PM
Last Post: Yoriz
  Outputting Sorted Text files Help charlieroberrts 1 1,684 Jul-05-2020, 08:37 PM
Last Post: menator01
  sorted function example mystery sabaidii2 4 2,480 Feb-10-2020, 09:37 AM
Last Post: DeaD_EyE
  Byte array is sorted when sending via USB daviddlc68 1 2,775 Aug-16-2019, 10:11 AM
Last Post: wavic
  sorted object in list trois 2 2,209 Mar-04-2019, 09:12 AM
Last Post: trois
  [Help] sorted() in while loop with user's input() {Screenshot attached} vanicci 5 3,952 Aug-04-2018, 08:59 PM
Last Post: vanicci

Forum Jump:

User Panel Messages

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