Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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

Isn't that kind of a deal-breaker?



It depends on you case.

If you are doing:

   slist = list(mylist) #create new copy of the list
   slist.sort() #sort the list
   use_sorted_list(slist)
The use of sorted is more more convenient, and really doesn't use more memory (since the memory from that statement you quoted is for the list copy).

More usefully: sorted will take anything that is iterable, allowing you to write simpler code, rather than testing for various types and dealing with them in type specific ways.


The benefit is only lost if you want to store the sorted mylist.

However, sorted() is useful if you want to create a list, sort it, use it, and throw it away... all in a single line.

The blog gives an example where a file is read, sorted and transformed. If he loaded the file to a list and sorted that list before transforming it, there would be an unnecessary copy of the list sitting around consuming memory.


He doesn't do a clean comparision.

If you have a list of data and need this data in a specific order and coincidentially iterate over this list every once in a while, then sorted will be less efficient, because you can sort in-place once.

If you have a list of data and you want to iterate over it in a specific order just this single time, you will need to spend a linear amount of memory to sort the list and then iterate over it.

In the first case, sorted() is not useful, because .sort() sorts in-place without additional memory overhead. In the second case, copy/.sort is required and just requires more code for pretty much the same effect. In this case, sorted() is just as bad as the alternative, but shorter.


And sorted() and reversed() behave differently (return different object classes) while mylist.sort() and mylist.reverse() do. In that way it's also confusing.

The modify-in-place method does seems more natural when you do want the destructive updating case.


Not at all. With .sort() you're suddenly injecting state into your code, with all the complexity that implies.


sometimes clarity and elegance win over performance




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: