Very interesting Rani!

I investigated this by making a replacement of the `len` function and
putting breakpoints inside of it.

The answer: When you call `list.sort`, it first empties the list, and then
starts measuring the length of the items for sorting. So when measuring the
list itself, it gets a result of 0 because the list has been emptied.

The question is: Is there a good reason for Python behaving like that?


Ram.

On Mon, Nov 14, 2011 at 2:01 AM, Rani Hod <[email protected]> wrote:

> Dear Abby,
>
> Any idea why sorted and list.sort behave differently in the following
> example?
> (specifically, why x is not sorted in the end?)
>
> Thanks,
> R.
>
> ------------8<--------------------8<--------
> >>> x = ['one','two','three']; x.append(x)
> >>> sorted(x, key=len)
> ['one', 'two', ['one', 'two', 'three', [...]], 'three']
> >>> x.sort(key=len); x
> [[...], 'one', 'two', 'three']
> ------------8<--------------------8<--------
>
> _______________________________________________
> Python-il mailing list
> [email protected]
> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>
>
_______________________________________________
Python-il mailing list
[email protected]
http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il

לענות