odd behavior

Kristian Zoerhoff kristian.zoerhoff at gmail.com
Fri Nov 11 14:40:02 EST 2005


On 11 Nov 2005 11:34:47 -0800, Greg <gstgeorge at gmail.com> 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?

The key option defaults to an alphabetic sort *every time* you call
sort, so if you want to change this, you must call for your sort key
each time. To do what you want, roll the sorts into one step:

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


--
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org



More information about the Python-list mailing list