Python List sorting with key argument explored
Everybody uses lists as an array to store values. List provide a lot of in-build features.
Lots of reasons to use lists. I think, one of the most used features is sorting. Internally , python uses Merge sort technique to sort the array items. But the sort method can be used in many other ways to have more control.
The python help says:
Things to note: The sort method doesn't return anything. It saves the changes in the list permanently. Thats why it is faster than the method sorted
If elements are strings, they gets sorted by alphabetical order.
SORT IN REVERSE ORDER
Using the KEY argument.
Perhaps the most versatile of all is the "key" argument. The value of the key parameter should be a function that takes a single argument and it returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
What above code shows is, I want to sort alphabetically by the rules of ascii , in reverse order. This is not so convincing I assume. Perhaps a much interesting example.
Sort by Length of string
In the above case, we are sorting by length of strings.
So we actually now have a list : [3, 1, 2] .
Hence the result,
['b', 'ab', 'abc']
[1 , 2, 3]
Sort by case (Upper)
When we specify str.upper, we are saying - Treat every element as UPPER CASE, then sort.
So we are sorting ['ABC', 'A', 'AB']
As a result, we get ['A', 'AB', 'ABC']
Sort by case (Lower)
Sort by last letter
I want to sort by the last letter of each word. Essentially this is how we manually do it.
Step 1 : Extract last letter of each word and keep in a list
Step 2 : Sort that list
Step 3 : Relatively display the original list but sorted.
For the Step 1 , we have used a function created using lambda. This function accepts a string and returns it's last letter.
Zeros as least preference
I have a list of numbers with some zeros in it . I want to have the list sorted , but I also want all the zeros at the end.
Original list : l = [4,0,3,0,8,0,1]
Expected list after sorting: [1, 3, 4, 8, 0, 0, 0]
There are many ways to do it. I'll use what comes to my mind first.