Talk about the difference between the list.sort() method and the function sorted() in Python

(1) list.sort() method

The list.sort() method sorts in-place, which means it will directly act on the current list and directly turn the current list into a sorted list. It will return None. In Python, if a function or method modifies an object in place, generally speaking, they will return None. The purpose of this is to let the users of the API know that this function or method is modified in place. For example, the random.shuffle function also has this feature.

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

There are advantages and disadvantages, because these functions or methods can only return None, so they cannot be connected one by one like streaming programming.

(2) The built-in function sorted()

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

(3) Keyword parameters

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

Keyword parameter Defaults Description
reverse False Reverse order
key Value sort Sorting algorithm; str.lower: sort by ignoring case; len: sort based on string length

(4) Example

Luciano Ramalho gave such 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)

operation result:

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']

You can see that the list.sort() method is sorted in place, and the sorted() function does not affect the original object, it will return a new object that has been sorted.

Guess you like

Origin blog.csdn.net/deniro_li/article/details/108893027