sort() doesn't work on dist.keys() ?
Mel Wilson
mwilson at the-wire.com
Thu Jul 10 16:59:36 EDT 2003
In article <6cd58b6.0307101214.34e99f2a at posting.google.com>,
spinard at ra.rockwell.com (Steve Pinard) wrote:
>New to Python, so please bear with me.
>
>>>> import sys
>>>> print sys.modules.keys() # works fine
>['code', ...snip... ]
>>>> print sys.modules.keys().sort() # returns None, why?
>None
>
>According to my reference (Nutshell), keys() returns a
>"copy" of the dict keys as a list, so I would expect when
>I aply sort() to that list, I would get an in-place sorted
>version of that list. Why do I get None?
Because [ ... what everybody else said ]
Apparently the designer of sort didn't want anyone to
mistakenly think that
sorted_version = my_list.sort()
would leave them with a sorted list *and* an intact,
unsorted list.
Lots of people have asked this. Maybe in the long run
you want to write a module of your own contining something
like
def sorted_copy (a_sequence, *varargs):
ret = list (a_sequence)
ret.sort (*varargs)
return ret
and put it in site_packages, or somewhere where you can
re-use it easily. *varargs is there to stand for the
optional comparison function in a_list.sort(cmpfunc).
Regards. Mel.
More information about the Python-list
mailing list