-->

Python sort arrays with sorted method

By: Varghese Chacko 1 year, 5 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. 

sorted

This method sorts the list and returns the new array

example:

>>> 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.

Example:

>>> 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.

Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.