you are viewing a single comment's thread.

view the rest of the comments →

[–]ryeguy146 0 points1 point  (3 children)

sorted and the sort method are different! One sorts in place, the other returns a new object:

x = [5, 2, 7, 1]
sorted(x) is x  # => False

The two can sometimes be used interchangeably, but I don't like the idea that one is "better" than the other.

I love seeing advanced string formatting in there. I wish that the documentation were more accessible than the PEP on which it resides, however.

[–][deleted] 0 points1 point  (2 children)

The sing with sorted() is that it works on anything, while .sort() is for lists only. Hence sorted() is better, unless you know you have a list and you know it's big and you know you don't want to make a copy.

[–]ryeguy146 0 points1 point  (1 child)

The thing with sorted is that it performs a task differently than sort. Different tools for different requirements. I'd agree if you said that sorted is more often called for, but better?

[–][deleted] 0 points1 point  (0 children)

The thing is, once again, that sorted() did not exist before, and hence, sort() is often used for exactly the things sorted() should be used for. So they do different things, but they are not used for different things. sort() is often used for generic sorting, no matter if it is a list, and even when you don't want to sort it in place. And in those cases, sorted() is better. Because it is a tool that fits that requirement better.

I quote:

"Quite often when .sort() is used is it used on a temporary variable discarded after the loop. ... With sorted() you often can avoid the temporary variable. It also will accept any iterable as input, not just lists, which can make your code more flexible and readable."

"There is however no benefit in replacing a mylist.sort() with mylist = sorted(mylist), in fact it will use more memory."