News for hackers. Stuff that matters.
Re:Improving your (Python) code with modern idioms by joejohnson on Tuesday May 08, 2012 @12:46AM (#3942303)
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?

Re:Improving your (Python) code with modern idioms by sophacles on Tuesday May 08, 2012 @01:33AM (#3942399)
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.

Re:Improving your (Python) code with modern idioms by dbecker on Tuesday May 08, 2012 @01:50AM (#3942428)
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.

Re:Improving your (Python) code with modern idioms by tetha on Tuesday May 08, 2012 @06:24AM (#3942995)
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.

Re:Improving your (Python) code with modern idioms by probably on Tuesday May 08, 2012 @12:57AM (#3942322)
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.

Re:Improving your (Python) code with modern idioms by mattdeboard on Tuesday May 08, 2012 @08:26AM (#3943265)
Not at all. With .sort() you're suddenly injecting state into your code, with all the complexity that implies.
Re:Improving your (Python) code with modern idioms by VMG on Tuesday May 08, 2012 @08:01AM (#3943191)
sometimes clarity and elegance win over performance