Python Provides two ways to sort lists , Built in list method list.sort()
And built-in functions sorted()
. Although both will sort the elements of the list , But if you don't use it properly , They may produce unexpected or undesirable results .
The main difference between the two is list.sort()
The list will be sorted in place , Change its index and return None
, and sorted()
A new sort list will be returned , The original list remains unchanged . Another difference is sorted()
Accept any iteratable whilelist.sort()
yes list
Class method , And can only be used with lists .
nums = [2, 3, 1, 5, 6, 4, 0]
print(sorted(nums)) # [0, 1, 2, 3, 4, 5, 6]
print(nums) # [2, 3, 1, 5, 6, 4, 0]
print(nums.sort()) # None
print(nums) # [0, 1, 2, 3, 4, 5, 6]
both list.sort()
and sorted()
All have the same key
Optional reverse
Parameters , And you can call... On each list element before comparing .
list.sort()
It should be used when you want to change the list and do not need to retrieve the original order of the elements . On the other hand ,sorted()
When the object to be sorted is an iteratable object ( For example, a list of 、 Tuples 、 Dictionaries 、 character string ) And the expected result is a sorted list of all elements , It should be used .