Python sort arrays in place with built in sort() method

By: Varghese Chacko 1 year, 2 months ago

Python provides two methods to sort an array. First one is list.sort() which sorts the array in place where as sorted returns the sorted array and will not change the original array. 

list.sort

This method sorts the list in place, using only < comparisons between items. If any comparison operations fail, the entire sort operation will fail and the list will likely be left in a partially modified state.

example:

>>> a = ['q', 'w', 'r', 'e', 't', 'y']
>>> a.sort()
>>> a
['e', 'q', 'r', 't', 'w', 'y']

The sort accepts two arguments. First one is the key to sort. For example, if we want to sort case-insensitive, we can use the string.lower as the key. 

>>> a = ['q', 'w', 'r', 'E', 'T', 'y', 'A','S','D','F', 'i', 'k']
>>> a.sort()
>>> a
['A', 'D', 'E', 'F', 'S', 'T', 'i', 'k', 'q', 'r', 'w', 'y']

>>> a.sort(key=str.lower)
>>> a
['A', 'D', 'E', 'F', 'i', 'k', 'q', 'r', 'S', 'T', 'w', 'y']
>>> 

You may notice that, in above case, first sort is done case sensitive where as second one is case-insensitive.

Second argument is reverse, which specifies to sort ascending or descending, defaults to False.

Example:

>>> a = ['q', 'w', 'r', 'E', 'T', 'y', 'A','S','D','F', 'i', 'k']
>>> a.sort(reverse=True)
>>> a
['y', 'w', 'r', 'q', 'k', 'i', 'T', 'S', 'F', 'E', 'D', 'A']
>>> a.sort(reverse=False)
>>> a
['A', 'D', 'E', 'F', 'S', 'T', 'i', 'k', 'q', 'r', 'w', 'y']

With both reverse and key

>>> a = ['q', 'w', 'r', 'E', 'T', 'y', 'A','S','D','F', 'i', 'k']
>>> a.sort(key=str.lower, reverse=True)
>>> a
['y', 'w', 'T', 'S', 'r', 'q', 'k', 'i', 'F', 'E', 'D', 'A']
>>> a.sort(key=str.lower, reverse=False)
>>> a
['A', 'D', 'E', 'F', 'i', 'k', 'q', 'r', 'S', 'T', 'w', 'y']
>>> 

we can specify our own custom methods as key to have advanced sorting, which will be discussed in another blog.