Fix Python – Why do python lists have pop() but not push()

Question

Asked By – Eddie Welker

Does anyone know why Python’s list.append function is not called list.push given that there’s already a list.pop that removes and returns the last element (that indexed at -1) and list.append semantic is consistent with that use?

Now we will see solution for issue: Why do python lists have pop() but not push()


Answer

Because “append” existed long before “pop” was thought of. Python 0.9.1 supported list.append in early 1991. By comparison, here’s part of a discussion on comp.lang.python about adding pop in 1997. Guido wrote:

To implement a stack, one would need
to add a list.pop() primitive (and
no, I’m not against this particular
one on the basis of any principle).
list.push() could be added for
symmetry with list.pop() but I’m not
a big fan of multiple names for the
same operation — sooner or later
you’re going to read code that uses
the other one, so you need to learn
both, which is more cognitive load.

You can also see he discusses the idea of if push/pop/put/pull should be at element [0] or after element [-1] where he posts a reference to Icon’s list:

I stil think that all this is best
left out of the list object
implementation — if you need a stack,
or a queue, with particular
semantics, write a little class that
uses a lists

In other words, for stacks implemented directly as Python lists, which already supports fast append(), and del list[-1], it makes sense that list.pop() work by default on the last element. Even if other languages do it differently.

Implicit here is that most people need to append to a list, but many fewer have occasion to treat lists as stacks, which is why list.append came in so much earlier.

This question is answered By – Andrew Dalke

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0