## The difference between sort() and sorted() in python (this is a big hole)

qinjianhuang 2020-11-13 05:23:01
difference sort sorted python big

In today's LeetCode When you brush the questions, you need to use the sorting function , At first, I didn't realize the difference between the two sort functions , Resulting in code errors , Special post .

First of all, these two functions can realize the sorting function , But there are many different principles . First look at the following code ：

``````listA = [1, 3, 6, 3, 2]
newList_1 = listA.sort()
print(listA)
print(newList_1)``````

The output is zero ：

``````[1, 2, 3, 3, 6]
None``````

Youmu feels strange , Why? listA The value of becomes the sorted result , however newList_1 nevertheless None Well ？ View source code ：

``````def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
""" L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
pass``````

original sort() The method is to sort directly on the original list , No new list is returned , So the return value is None！

I want to see others ：

``````listA = [1, 3, 6, 3, 2]
newList_2 = sorted(listA)
print(newList_2)
print(listA)``````

The output is zero ：

``````[1, 2, 3, 3, 6]
[1, 3, 6, 3, 2]``````

Isn't it amazing ？listA Nothing has changed , But the returned results are sorted lists . Let's look at the source code ：

``````def sorted(*args, **kwargs): # real signature unknown
"""
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
pass``````

From the above we can see that ,sorted() After the function is ordered, it returns a new list , The original list hasn't changed ！

Hi , It's really awesome , My brother ！