10

I am quite often using Python instead of pseudocode. For that, I would like to have a stack. I know that using lists is the way to go (source), but I would like to use myList.push rather than myList.append to make clear that I use a stack.

I thought I could do something simple like

myList.push = myList.append

to define an alias for the append operation, but I get

    stack.push = stack.append
AttributeError: 'list' object has no attribute 'push'

Does a short solution for adding a push-operation to a list exist?

(It should not mess up my runnable Python-pseudocode)

2
  • btw - see stackoverflow.com/questions/1566266/… Commented Aug 7, 2012 at 7:30
  • so your question is really can you assign an alias to list.append(x) where the alias would be something like push(x) ? Commented Aug 7, 2012 at 7:49

4 Answers 4

18

You can make a subclass of list like this:

class List(list):
    def push(self, x):
        self.append(x)

Use your custom class the same way you would use a regular list:

>>> s = List()
>>> s.push(10)
>>> s.push(20)
>>> s
[10, 20]
Sign up to request clarification or add additional context in comments.

5 Comments

doesn't "push" add it to the front? in which case .insert(0,x) should be used.
deques will be faster than lists for this purposes.
@monkut: that sounds reasonable, however, the inverse operation (list.pop) pops the last item off the list by default. So it's better to implement push with list.append so you don't have to pop(0) or override pop in the subclass.
good point, I wasn't thinking of pop. Probably better to use append then.
For a LIFO stack, subclass from list, make push() delegate to append() for adding values, and use pop() for removing values. For a FIFO queue, subclass from collections.deque, make push() delegate to appendleft(), and use pop() for removing values.
5

Instead of redefining, how about aliasing the same function ?

class List(list):
    def __init__(self):
        self.push = self.append

This would retain the functionality of append too.

1 Comment

This is OK. To preserve list construction semantics (e.g. List((1,2,3,4)) you could make the __init__ method accept *args and **kwargs and then pass these to the base class __init__ via super(List, self).__init__(*args, **kwargs)
2
>>> a = []
>>> push  = a.append
>>> push(1)
>>> a
[1]
>>> 

1 Comment

Thanks for your answer. This is what I thought of but couldn't remember. Though, I accepted the other answer as I think adding 3 lines to my pseudocode is ok and the result looks a little bit cleaner => +1 for your answer
1
>>> stack = type('stack', (list,), {'push':list.append})()
>>> stack.push(1)
>>> stack.pop()
1
>>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.