I want to sort a list of tuples by their second elements.
Example input:
[("Bob",3),("Terry",1)]
Example output:
[("Terry",1)("Bob",3)]
By using the sort() method we can easily sort the list of tuples alphabetically. To do this task first we have to create a function and pass the list as an argument. In the sort method, the key parameter is set to sort the element by using the lambda function.
Using sorted() function or in place sort are the ways to Sort a list of tuples by the first element in Python. Both methods need to use the key keyword. Note: key should be a function that identifies how to retrieve the comparable element from your data structure.
Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.
Another cool trick is to use on
from Data.Function:
import Data.Function (on)
import Data.List (sortBy)
sortBy (compare `on` snd) [...]
Not much different than comparing
but a nice trick from time to time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With