Python @ DjangoSpin

Python: The builtin sorted() in detail

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

sorted() in Python

sorted() in Python

You can use the command sorted(list1) to sort the elements of a list. You can give it a custom comparison function, and for more complex elements you can include a key function that pulls out a ranking property from each element for comparison.

Python's builtin sorted() function sorts the elements an iterable object in ascending order and returns a list of the ordered elements.

>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(...)
    sorted(iterable, key=None, reverse=False) --> new sorted list
	
	
### EXAMPLES ###
>>> anUnsortedList = [3, 6, 1, 2]
>>> sorted(anUnsortedList)
[1, 2, 3, 6]

>>> anUnsortedString = 'bca'
>>> sorted(anUnsortedString)
['a', 'b', 'c']

The optional keyword argument reverse, when set to True, arranges the elements in descending order. The default value of this argument is False.

>>> anUnsortedList = [3, 6, 1, 2]
>>> sorted(anUnsortedList, reverse = True)
[6, 3, 2, 1]

>>> anUnsortedString = 'bca'
>>> sorted(anUnsortedString, reverse = True)
['c', 'b', 'a']

The optional keyword argument key takes a function name in its keyword form i.e. without parentheses. The function so mentioned must be capable of taking each element of the provided iterable object, and it must be capable of returning a comparable value, such as ord(), sum() etc. The order of the resultant list is decided on the basis of values returned by this function. The default value for the key argument is None, meaning that the elements are compared directly i.e. using the ord() function on corresponding elements of entries. The builtin ord() function takes a single character(special ones too) and returns its Unicode value. Unicode is a collection of codes for more than 1,20,000 characters covering letters, numbers in a variety of languages, including symbols. Unicode values for letters a through z are 97 to 122 & A through Z are 65 to 90. The ord() function is inverse of the builtin chr() function.

>>> sorted( [ (1,5), (2,3), (3,4) ] )
[(1, 5), (2, 3), (3, 4)]												# ord('1') < ord('2') < ord('3')

>>> sorted( [ 'apple', 'aardvark', 'an' ] )								
['aardvark', 'an', 'apple']												# since all entries start with 'a', next elements are compared i.e. ord('a') < ord('n') < ord('p')

>>> sorted( [ (1,5), (2,3), (3,4) ], key = sum )
[(2, 3), (1, 5), (3, 4)]												# 2 + 3 < 1 + 5 < 3 + 4

That's all there is to the sorted() function. I hope this article enhanced your understanding of it. See you again some time!


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply