Search code examples
python-3.xstackimmutable-collections

implementing immutable stack in python


Have a question about creating new objects using existing objects in python. Example: I want to implement immutable Stack using python. However, catch here is, whenever I am creating new object, it should be created from existing object: in below example, how can I update push function to create a copy of s1 from s0 and append value 2 to S1?

class Stack:
    def __init__(self):
        self.items = []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[-1]
    def __str__(self):
        return str(self.items)

if __name__ == "__main__":
    s0 = Stack()
    s1 = s0.push(2)
    s2 = s1.push(3)

Solution

  • You just need a way to create a new Stack object with a copy of the existing items.

        def __init__(self, contents=[]):
            self.items = contents
        def push(self, item):
            new_stack = Stack(self.items[:]]
            new_stack.items.append(item)
            return new_stack