Can someone explain why this sorting will not work?

For example, if I have a list like this:

List1 =[7,6,9] List1 = List1.sort() 
+6
source share
2 answers

list.sort() sorts the list in place and returns None , so you actually assigned this return value to List1 , i.e. None .

 >>> List1 =[7,6,9] >>> repr(List1.sort()) 'None' #return Value of list.sort >>> List1 #though list is sorted [6, 7, 9] 

The built-in sorted function, on the other hand, returns a new sorted list:

 >>> List1 =[7,6,9] >>> sorted(List1) [6, 7, 9] >>> List1 #List1 is not affected [7, 6, 9] 

You can assign the result sorted to List1 , but that doesn't make sense, since list.sort will do the same thing in less time.

 >>> List1 = sorted(List1) >>> List1 [6, 7, 9] 

Although the above code was similar to list.sort , but actually it is a little different because it returns a new list. Example:

 >>> List1 =[7,6,9] >>> List2 = List1 # both List1, List2 point to the same object [7, 6, 9] >>> List1.sort() # sort List1 in-place, affects the original object >>> List1, List2 ([6, 7, 9], [6, 7, 9]) # both variables still point to the same list >>> List1 =[7,6,9] >>> List2 = List1 #same as above >>> List1 = sorted(List1) #sorted returns a new list, so List1 now points to this new list >>> List1, List2 #List2 is still unchanged ([6, 7, 9], [7, 6, 9]) 

Terms of comparison:

 >>> from random import shuffle >>> lis = range(10**5) >>> shuffle(lis) >>> %timeit lis.sort() 1 loops, best of 3: 9.9 ms per loop >>> lis = range(10**5) >>> shuffle(lis) >>> %timeit sorted(lis) 1 loops, best of 3: 95.9 ms per loop 

So, sorted should be used only when you do not want to influence the original list and want to assign a sorted version of this list to some other variable.

Besides lists of other data structures such as set , tuples , dicts , etc. don't have their own .sort() method, so sorted is the only thing you can use there.

 >>> s = {1,5,3,6} # set >>> sorted(s) [1, 3, 5, 6] 

help sorted :

 >>> print sorted.__doc__ sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list 
+14
source

.sort() sorts the list in place. It does not return a new list. Infact, since it returns nothing by default, it returns None .

If you want the sorted list to be returned, you can use sorted() :

 List1 = sorted(List1) 
+6
source

Source: https://habr.com/ru/post/947427/


All Articles