move to end, in Python 3.2 Really?
nn
pruebauno at latinmail.com
Tue Jan 18 13:39:43 EST 2011
On Jan 18, 12:20 am, Raymond Hettinger <pyt... at rcn.com> wrote:
> 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
Ah that is where it came from! I didn't remember popitem used that API
too. If you use them together it has a nice symmetry. I guess it is
just that "end" is more confusing than "pop" in that context.
Considering the precedence of popitem I withdraw my objection. I still
think it looks a bit odd but it is not unreasonable either. Sometimes
ugly consistency trumps beautiful inconsistency; c'est la vie...
More information about the Python-list
mailing list