(1) list.sort(

The list.sort() method sorts in-place, which means that it applies directly to the current list, making it a sorted list. It will return None. In Python, if a function or method makes an in-place change to an object, they generally return None. The purpose is to let the API user know that the function or method is an in-place modification operation. For example, the random. Shuffle function also has this feature.

The shuffle() method randomly sorts all the elements of the sequence.

The pros and cons are that these functions or methods only return None, so you can’t concatenate them as you would in streaming programming.

(2) Built-in function sorted()

The built-in sorted function accepts any type of iterable as an input parameter and internally creates a new list as the return value.

(3) Keyword parameters

Both the list.sort() method and the built-in sorted() function have the following two optional keyword arguments.

Keyword parameter The default value instructions
reverse False Whether to reverse
key sorted Sorting algorithm; Str.lower: sort regardless of case; Len: Sort based on string length

(4) Examples

Luciano Ramalho gives an example to illustrate the difference between the list.sort() method and the function sorted().

fruits=['grape','raspberry','apple','banana']
result=sorted(fruits)
logging.info('sorted(fruits) -> %s',result)
logging.info('fruits -> %s',fruits)

result=sorted(fruits,reverse=True)
logging.info('sorted(fruits,reverse=True) -> %s',result)

result=sorted(fruits,key=len)
logging.info('sorted(fruits,key=len) -> %s',result)

result=sorted(fruits,reverse=True,key=len)
logging.info('sorted(fruits,reverse=True,key=len) -> %s',result)

result=fruits.sort()
logging.info('sort() -> %s',result)
logging.info('fruits.sort() from fruits-> %s',fruits)
Copy the code

Running results:

INFO - sorted(fruits) -> ['apple', 'banana', 'grape', 'raspberry']
INFO - fruits -> ['grape', 'raspberry', 'apple', 'banana']
INFO - sorted(fruits,reverse=True) -> ['raspberry', 'grape', 'banana', 'apple']
INFO - sorted(fruits,key=len) -> ['grape', 'apple', 'banana', 'raspberry']
INFO - sorted(fruits,reverse=True,key=len) -> ['raspberry', 'banana', 'grape', 'apple']
INFO - sort() -> None
INFO - fruits.sort() from fruits-> ['apple', 'banana', 'grape', 'raspberry']

Copy the code

As you can see, the list.sort() method sorts in place, whereas the sorted() function does not affect the original object and returns a new sorted object.