4.6 Using sorted() and reversed() to change the order
Python’s sorted() function produces a new list by rearranging the order of items in a list. This is similar to the way the list.sort() method changes the order of list.
Here’s the important distinction between sorted(aList) and aList.sort():
- The - aList.sort()method modifies the- aListobject. It can only be meaningfully applied to a- listobject.
- The - sorted(aList)function creates a new list from an existing collection of items. The source object is not changed. Further, a variety of collections can be sorted. A- setor the keys of a- dictcan be put into order.
There are times when we need a sequence reversed. Python offers us two approaches to this: the reversed() function, and slices with reversed indices.
For example, consider performing a base conversion to hexadecimal or binary. The following code is a simple conversion function:
from collections.abc import Iterator 
 
def digits(x: int, base: int) ->... 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                