move to end, in Python 3.2 Really?

Raymond Hettinger python at rcn.com
Tue Jan 18 00:20:48 EST 2011


On Jan 17, 6:51 pm, nn <prueba... at latinmail.com> wrote:
> ...But the api on this baffles me a bit:
>
> >>> d = OrderedDict.fromkeys('abcde')
> >>> d.move_to_end('b', last=False)
> >>> ''.join(d.keys)
>
> 'bacde'
>
> I understand that "end" could potentially mean either end, but would
> "move_to_end" and "move_to_beginning" not have been clearer?

The default (and normal usage) is to move an item to the last
position.
So, od.move_to_end(k) becomes a fast equivalent to v=d.pop(k)
followed by d[k]=v.

The less common usage of moving to the beginning is done with
last=False.  This parallels the existing API for od.popitem():

>>> od = OrderedDict.fromkeys('abcdefghi')
>>> od.move_to_end('c')               # default case:  move to last
>>> od.popitem()                      # default case:  pop from last
('c', None)
>>> od.move_to_end('d', last=False)   # other case:    move to first
>>> od.popitem(last=False)            # other case:    pop from first
('d', None)

The existing list.pop() API is similar (though it takes an index
value instead of a boolean):

>>> mylist.pop()                      # default case:  pop from last
>>> mylist.pop(0)                     # other case:    pop from first

Those were the design considerations.  Sorry you didn't like the
result.


Raymond



More information about the Python-list mailing list