[Tutor] What's the difference between sort(aList) and aList.sorted()

Steven D'Aprano steve at pearwood.info
Wed Jul 26 20:21:11 EDT 2017


On Wed, Jul 26, 2017 at 02:40:17PM -0400, C W wrote:

> sorted(aList)
> > [2, 3, 4, 5]

sorted() makes a copy of whatever you give it, as a list, and sorts the 
copy. It doesn't have to be a list to start with:

py> sorted("alphabet")
['a', 'a', 'b', 'e', 'h', 'l', 'p', 't']


> aList.sort()
> aList
> > [2, 3, 4, 5]

The sort() method only works on actual lists, and it sorts the list in 
place, just as list.reverse() reverses the list, list.append() appends a 
value to the list, list.insert() inserts a value into the list, etc.

> Why is there both? They do the same thing. Is if I unknowingly hit the
> keyboard with the aList.sort(), then the "damage" is permanent.

They don't do the same thing. sorted() makes a copy of the argument 
first, list.sort() does not.

We have both because sometimes one is useful and other times the other 
is useful. Originally, and for many years, Python only had list.sort(), 
and if you wanted to sort a copy you had to write:

blist = list(alist)
blist.sort()

which is always a minimum of two lines and not very convenient. So it 
was eventually decided to add sorted().



-- 
Steve


More information about the Tutor mailing list