I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.
For example:
l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]
if I sort by element 1:
l.sort(key=itemgetter(1), reverse=True)
This will sort on the alphabetical ranking of the strings, not the length. I would prefer to sort in-place and reverse sort, with longest string first.
I can use a lambda and cmp,
l.sort(lambda x,y: cmp(len(x[1]), len(y[1])), reverse=True)
but is there a more elegant, or pythonic way using key and/or itemgetter?
Therefore, we can simply use the sort() method to sort a list. First, we will take an unsorted list of tuples and then call the sort() method. The sort() method will change the order from increasing (ascending) to decreasing (descending) when we pass the parameter reverse=True as an argument.
Custom Sorting With key= For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.
Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable.
In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().
Well you can make the lambda simpler:
l.sort(key=lambda t: len(t[1]), reverse=True)
Also, don't use list
as a variable name; it's already taken by a built-in function.
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