Differences between sort and sorted functions in python
list.sort()
is a list method and can be used with lists onlylist.sort()
sorts list in-place, so the original order is lostlist.sort()
returnsNone
sorted()
is a built-in function and can be used with any iteratorsorted()
returns sorted iterator leaving the original and its order unchangedsorted(list)
returns the sorted list
Though
list.sort() and sorted(list) have the same key and reverse optional arguments and can be called on each list element prior to making comparisons, there are many differences between them:
|
The function
sorted() did not have to be defined. It’s a built-in function that is available in a standard installation of Python. The sorted() function, with no additional arguments or parameters, is ordering the values in numbers in an ascending order, meaning smallest to largest. The sorted() function provides sorted output and does not change the original value in place. So, when sorted(list) is called, it provides an ordered list as a return value.There is no ordered output of list.sort() , so it returns None . The list will be sorted in place, and the original order is not maintained in any way.
|
list.sort() is a list method and can be used with lists onlysorted() is a built-in function and can be used with any iterator like list , tuple , set etc.
|
list.sort() returns None sorted(list) returns the sorted list
|
list.sort() sorts list in-place, so the original order is lostsorted(list) returns sorted list leaving the original list and its order unchanged
|
The primary difference between the two is that |