odd behavior

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Nov 11 22:32:26 EST 2005


On Fri, 11 Nov 2005 11:34:47 -0800, Greg wrote:

> Forgive me, and be kind, as I am just a newby learning this language
> out of M.L. Hetland's book.  The following behavior of 2.4.1 seems very
> strange

>>>> x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
>>>> x.sort(key=len)
>>>> x
> ['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>>> x.sort(reverse=True)
>>>> x
> ['aerate', 'add', 'acme', 'abalone', 'aardvark']

> The function called on line 4, at least to me, should work on x as it
> was on line 3, not the previously existing x on line 1.  What gives?

Why do you think it isn't operating on x as it is? The second sort is
sorting in reverse lexicographic order, which is the result you get.

I'm not running Python 2.4 so I can't test this, but to get the result you
want I guess you want this:

py> x.sort(key=len, reverse=True)
py> x
['aardvark', 'abalone', 'aerate', 'acme', 'add']

or:

py> x.sort(key=len)
py> x.reverse()


-- 
Steven.




More information about the Python-list mailing list