ok, so how do I return a sorted list without doing it in place

Grant Edwards grante at visi.com
Sat Feb 17 11:21:32 EST 2001


In article <96koqk$gv6$1 at panix2.panix.com>, Aahz Maruch wrote:

>>> I know I can do:
>>> 
>>> list = dict.keys()
>>> list.sort()
>>> .....
>>> 
>>> but it is just plain annoying.
>>
>>I agree. This has bitten me on the butt more than once. It also seems
>>somewhat unPythonic. Usually I expect what happens in Python, but that 
>>sort process always strikes me as unexpected.

On many occasions, I would find it quite handy if there was a sequence
method that returned a sorted shallow copy:

 for k in dict.keys().sorted():
   whatever(k) 

>It's unexpected in some respects, but doing it this way causes the
>fewest surprises overall.  At least you rarely get a downstream bug
>this way.

In my mine the used of the adjective "sorted" as a method name conveys the
fact that it doesn't modify the list in place they way the imperative "sort"
does.  YMMV.

-- 
Grant Edwards                   grante             Yow!  World War III? No
                                  at               thanks!
                               visi.com            



More information about the Python-list mailing list