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)
in operator in Python In Python, the in operator determines whether a given value is a constituent element of a sequence such as a string, array, list, or tuple. When used in a condition, the statement returns a Boolean result of True or False.
There are four methods to add elements to a List in Python. append() : append the element to the end of the list. insert() : inserts the element before the given index. extend() : extends the list by appending elements from the iterable.
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]
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.
>>> a = []
>>> push = a.append
>>> push(1)
>>> a
[1]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With