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

Fredrik Lundh fredrik at pythonware.com
Thu Jul 10 22:49:06 CEST 2003


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 sort returns None, not a reference to the list.
see the FAQ for details:

    http://www.python.org/doc/FAQ.html#6.20

to fix this, use the return key:

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

</F>








More information about the Python-list mailing list