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'
The built-in sorted function, on the other hand, returns a new sorted list:
>>> List1 =[7,6,9] >>> sorted(List1) [6, 7, 9] >>> List1
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
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}
help sorted :
>>> print sorted.__doc__ sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list