pop method question

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Mar 4 14:47:37 CET 2007

On Sun, 04 Mar 2007 07:36:50 -0500, Nicholas Parsons wrote:

> Hi Jordan,
> That is true what you say about pop() behavior with stack-like  
> objects.  But the definition of pop() for a stack-like structure is  
> stronger than that.

That's okay, we're not talking about pop for stack-like structures, we're
talking about pop for dictionaries.

> A stack is a LIFO data structure.  Therefore the  
> pop() operation is defined to not only mutate the receiver and return  
> the item popped but also ensure that the LAST item in the stack is  
> removed.

Not so. Pop can also be defined to take an argument telling the data
structure (not necessarily a stack) which item to remove.

Pop can also operate on queues, in which case it removes the FIRST item in
the queue.

Pop can also be defined for dequeues (double-ended queue), in which case
it can remove from either the first or the last position.

Pop can also be defined for balloons, which is what they do when you stick
a pin in them.

> This makes perfect sense for a list type in python since  
> lists are mutable sequences that have a specified order.  But for  
> dictionaries this does not hold since they are unordered sequences by  
> definition.  

That's okay, since unordered sequences can define pop too. Obviously pop
for a dictionary has to be defined slightly differently, but the essential
characteristics -- remove an item and return it -- remain the same.

> So for dictionaries it would not make sense for a  
> programmer to simulate a stack-like type.

Dictionaries don't simulate stacks.

We can talk about pushing a value onto a stack, and about pushing a
value into a register, and yet registers are not stacks. We use the
same word, multiply, for both scalar multiplication (3*5=15), matrix
multiplication, and mixed scalar-to-matrix multiplication, even though
they are quite different. (For starters, XY = YX if X and Y are both
scalars, but not if they are matrices.)

We use "concatenate" to describe the different procedures of joining
linked lists, arrays and strings. We talk about "inserting" into linked
lists, B-trees, heaps, arrays and priority queues.

Why shouldn't we talk about popping a value from a dictionary?

> While we're on the subject I'm also curious as to why the author of  
> the built-in list class called the method "append" to add an element  
> to the end of a list and not something like "push".

Well, gosh, I really don't know what they were thinking, using "append" as
the name of the method that, um, APPENDS an item to the end of a list. How
confusing is that?

> But this is not  
> really much of a problem if the programmer could create an alias for  
> it.

It isn't a problem at all.


More information about the Python-list mailing list