Python sort arrays with sorted method

By: Varghese Chacko 1 year, 2 months ago

Python provides a method sorted which returns the sorted array and will not change the original array, where as list.sort() with change the array in place. 


This method sorts the list and returns the new array


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

Please not that the original array didnt change.

The sorted accepts two optional 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']
>>> sorted(a, key=str.lower)
['A', 'D', 'E', 'F', 'i', 'k', 'q', 'r', 'S', 'T', 'w', 'y']
>>> a
['q', 'w', 'r', 'E', 'T', 'y', 'A','S','D','F', 'i', 'k']

You may notice that, in above case, array is sorted is case-insensitive and returned.

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


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

With both reverse and key

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

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