sort() doesn't work on dist.keys() ?

Bengt Richter bokr at oz.net
Fri Jul 11 01:45:39 EDT 2003


On 10 Jul 2003 13:14:01 -0700, spinard at ra.rockwell.com (Steve Pinard) wrote:

>(Got a comm error trying to post first time, sorry if this
>is a duplicate)
>
>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?
>
It's a reasonable question. Some would probably like it to work that way,
but it doesn't. Try it with any list:

 >>> any = [3,1,5,2,4,0]
 >>> any
 [3, 1, 5, 2, 4, 0]
 >>> print any.sort()
 None
 >>> any
 [0, 1, 2, 3, 4, 5]

The sort happens, but a reference to the result is not returned, just None.
In your example the temporary list gets sorted but doesn't get bound to a name
or other place so you can't get to it. So do it in two steps:

any = sys.modules.keys()
any.sort()

Now any should be what you want.

Regards,
Bengt Richter




More information about the Python-list mailing list