Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an operation to a list in Python?

Tags:

python

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)

like image 289
Martin Thoma Avatar asked Aug 07 '12 07:08

Martin Thoma


People also ask

Can we use operator in list in Python?

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.

Can you add functions to a list Python?

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.


3 Answers

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]
like image 198
Raymond Hettinger Avatar answered Oct 19 '22 04:10

Raymond Hettinger


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.

like image 5
Vinayak Kolagi Avatar answered Oct 19 '22 05:10

Vinayak Kolagi


>>> a = []
>>> push  = a.append
>>> push(1)
>>> a
[1]
>>> 
like image 2
Inbar Rose Avatar answered Oct 19 '22 05:10

Inbar Rose