ok, so how do I return a sorted list without doing it in place
r2d2 at mao.acc.umu.se
Mon Feb 19 03:14:35 EST 2001
In article <96kg77$88c at dispatch.concentric.net>, Phlip wrote:
>Proclaimed Sean 'Shaleh' Perry from the mountaintops:
>> So, several of us informed Philip that list.sort() is in place and returns
>> nothing. How do i accomplish:
>> for key in dict.keys().sort():
>> print "%s -> %s" % (key, dict[key])
>> I know I can do:
>> list = dict.keys()
>> but it is just plain annoying.
>I don't know why a more useful return value couldn't have been supplied,
>for call chaining like this at least, but Mr. Manners reminds the Gentle
>Poster that one should not cram too much stuff on one command line. Leave
>that for Perl or C++ coders.
I really like the way ruby has solved this, by providing two functions:
sort and sort!, where sort! sorts the list in place and sort returns a
sorted copy. The exclamation mark is used to denote a method that
changes the object in-place. With this convention you do not have to
remember whether a function works in-place or on a copy.
Many other similar functions also have two variants, for example there is
a map function and a map! function.
More information about the Python-list