Why do python lists have pop() but not push()

Viewed 265361

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?

12 Answers

From PEP 20 -- The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

Having both list.append and list.push would be two ways of doing the same thing -- and list.append came first.

I am a python newbie, for myself, I use this:

def push(one, array):
    array.append(one)
def pop(array):
    if len(array) > 0:
        one = array[len(array)-1]
        del array[len(array)-1]
        return one
    else:
        return None
def pop_first(array):
    if len(array) > 0:
        one = array[0]
        del array[0]
        return one
    else:
        return None

pop_first() is to add from beginning of the list (the opposite of pop())

I don't use append just to make my code more readable (from my point of view), since I also code in JS, flutter, and PHP, function name similarities is important.

Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.

If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.

Related