about sort and dictionary

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Nov 23 13:47:19 CET 2005


bonono at gmail.com <bonono at gmail.com> wrote:
>OKB (not okblacke) wrote:
>> Fredrik Lundh wrote:
>> > bonono at gmail.com wrote:
[ ... ]
>> >> > so what would an entry-level Python programmer expect from this
>> >> > piece of code?
>> >> >
>> >> >     for item in a.reverse():
>> >> >         print item
>> >> >     for item in a.reverse():
>> >> >         print item
>> >> >
>> >> I would expect it to first print a in reverse then a as it was.
>> >>
>> >> a=[1,2,3]
>> >>
>> >> I expect it to print
>> >>
>> >> 3
>> >> 2
>> >> 1
>> >> 1
>> >> 2
>> >> 3
>> > really?  wouldn't
>> >
>> >     3
>> >     2
>> >     1
>> >     3
>> >     2
>> >     1
>> >
>> > make a lot more sense ?
>>     	Yes.  The unintuitive thing is that the list is sorted in place at
>> all.
>intuitive seems to be a very subjective matter, depends on once
>background etc :-)

A quick straw-poll of some non-Pythonistas (two sysadmins, two
programmers) suggests that reversing in place is unintuitive --
all four expected:

3
2
1
3
2
1

as suggested by Fredrik. It was less clear-cut, talking through
it, whether they found sorting inplace was intuitive or not, but
it was agreed that it would be "odd" if sort() and reverse()
behaved differently. All of which is to say I'm convinced by the
current behaviour:

1. sort() in place makes sense in terms of space, and is not
   completely unintuitive.
2. reverse() should do what sort() does.
3. The inexperienced user is most likely to expect the above
   code to print 3 2 1 3 2 1, and is more likely to have
   difficulty tracking down the problem if reverse() returns
   self and they get unexpected results than if it returns
   None and they get a TypeError: iteration over non-sequence.

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list