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

C W tmrsg11 at gmail.com
Wed Jul 26 22:03:59 EDT 2017

```Thank you very much, all!

One other question: how do you look up a method?

>help(sort)
Traceback (most recent call last):

File "<ipython-input-1-1dcda44a1b89>", line 1, in <module>
help(sort)

NameError: name 'sort' is not defined

Back to function vs method, I came from R:

aList = sort(aList)

There was never aList.sort(), I was fine with it for years. I suppose
sort(aList) is more of a data science thing.

Thanks to all!

On Wed, Jul 26, 2017 at 8:21 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
```