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

Troels Therkelsen t_therkelsen at hotmail.com
Thu Jul 10 16:33:47 EDT 2003


In article <6cd58b6.0307101214.34e99f2a at posting.google.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?

>From the documentation of the mutable sequence sort() method, note (7):

   "The sort() and reverse() methods modify the list in place for
    economy of space when sorting or reversing a large list. To remind
    you that they operate by side effect, they don't return the sorted
    or reversed list."

Or, in other words, sort() always returns None.  If you want to sort, you
need to bind a name to the list you want to sort, first, then call sort() on 
it and then print the now sorted list. For example:

   sys_keys = sys.modules.keys()
   sys_keys.sort()
   print sys_keys

Hope this helps,

Troels Therkelsen





More information about the Python-list mailing list