The reason to publish the post was that during a detailed study of lists (arrays) in Python, I could not find on the web any simple description of the method of sorting elements using the key: list.sort(key=…).

Maybe, of course, I was so unlucky and for a long time I understand simple things for everyone, but I think that the information below will be very useful to the same novice pythonists as myself.

So, what we have. Suppose we have a list that we would like to sort — and it consists of three rows of different lengths in a certain sequence:

sortList = ['a', 'cc', 'bbb']

Sorting of array elements by the .sort() method is performed lexicographically by default — in other words, in alphabetical order, as well as from a smaller value to a larger one. So if we do:

sortList.sort()

then we get at the output:

>>> ['a', 'bbb', 'cc']

However, the .sort() method allows us to change both the principle and the sorting order.

To change the sorting principle, the keyword key is used, which has become available since Python version 2.4.

Suppose we would like to sort our list in two ways: 1. in alphabetical order; 2. by line length. The first method, however, already works as a default sort, but we can achieve the same results using the key parameter:

sortList = ['a', 'cc', 'bbb']

# Creating an “external” function that will sort the list in alphabetical order:

sortByAlphabet(inputStr):
return inputStr[0] # The key is the first character in each line, sort by it

# The second function that sorts the list by the length of the string:

def sortByLength(inputStr):
return len(inputStr) # The key is the length of each row, sort by length

print u’ Source list: ‘, sortList # >>> [‘a’, ‘cc’, ‘bbb’]

sortList.sort(key=sortByAlphabet) # Each element of the array is passed as a parameter
to the print u function’Sorted alphabetically: ‘, sortList # >>> [‘a’, ‘bbb’, ‘cc’]

sortList.sort(key=sortByLength) # Each element of the array is passed as a parameter
to the print u function’Sorted by string length: ‘, sortList # >>> [‘a’, ‘cc’, ‘bbb’]

# Now let’s sort by the length of the string, but in reverse order:

sortList.sort(key=sortByLength, reverse=True) # In reverse order
print u’Sorted by string length, in reverse order: ‘, sortList # >>> [‘bbb’, ‘cc’, ‘a’]

Note that the .sort() method performs actions with the source list, rearranging elements inside it itself, and DOES NOT return a sorted copy of the source list. To get a sorted copy, use the sorted method:

newList = sorted(sortList)

— or the same option, but with the key parameter (similar to the one described above):

newList = sorted(sortList, key=sortByLength)

The .sorted() method has other parameters, but they didn’t seem so confusing to me for independent parsing.

Tags:

Leave a Reply