Learn Python by Building Data Science Applications
上QQ阅读APP看书,第一时间看更新

The sorted function

This function takes an iterable as an input and returns it, sorted. This function can take two additional arguments—reverse (Boolean) and key (iterable). The reverse argument allows us to get the values in reverse order, from big to small. key, if specified, is expected to be of the same length as the first one and will be used to sort by. 

Let's look at the following example:

>>> sorted('Hi there!')
[' ', 'H', 'e', 'e', 'h', 'i', 'r', 't']

>>> sorted('Hi there!', reverse=True)
['t', 'r', 'i', 'h', 'e', 'e', 'H', '!', ' ']

The next function does not expect you to pass an iterable—instead, it generates one.