Tuesday, April 10, 2018

Python: key = lambda usage explained in Sorted()

After a long long time, just documenting the usage of key = lambda anonymous function inside sorted()/sort() function.

Below is a beautiful explanation Posted by Paul G for a Python beginner lost in aspects of Python.

For the Python code:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)
[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?
Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:
Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.
We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.
What does the example using a modulo return? A boolean value: True=1, False=0. So how does sorted deal with this key? It bascially transforms the original list to a sequence of 1s and 0s.
[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]
Now we're getting somewhere. What do you get when you sort the transformed list?
[0,0,0,1,1,1,1]
Okay, so now we know why the odds come before the evens.

Link: https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda

No comments:

Post a Comment