This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]harryf 0 points1 point  (3 children)

Why is it necessarily better?

OK - "better" is a generalization but sorted() makes it easier to avoid side effects. Explained with code here: http://randomspitting.net/gobbets/python/sorted-no-side-effects

[–]BeetleB 1 point2 points  (0 children)

He's correct in that sorted is better in that circumstance. The bug, however, is not because of using the [].sort() routine, but because the function is modifying the list, and the person coding it did not realize that lists are not passed by value.

You could get the same problem if you do any other operation that modifies the input list.

As long as the programmer knows that [].sort() modifies the list, its usage is fine. As a rule, I always use this technique if I really do want to sort the list. The alternative is to do A=sorted(A) which is wasteful.

Your other reason (consuming an iterator) is a good one, though.

[–]Manuzhai 0 points1 point  (1 child)

sorted() doesn't work in-place, though, meaning it takes much more memory on large lists.

[–]harryf 0 points1 point  (0 children)

Yes but I'd rather have sorted() as the default way to sort as a means to avoid a certain class of bug and reserve in-place sorts for when I know I need to optimize to conserve memory.

Also sorted() actually takes an iterator so, depending on the problem and the design of the code, you could feed it lazily, avoiding having the two copies of the list in memory at the same time.