Python3 Stack implementation with List built-in - Round Two Previous code is available at Python3 Stack implementation with List built-in, this is a second-round review after I made alterations.


Once again, let's review my Stack implementation, with built-in lists, and with review notes from the prior review implemented.

Any changes and suggestions are welcome!





class Stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def pop(self):
        if len(self) == 0:
            raise IndexError("You cannot pop from an empty stack.")

        return self._stack.pop()

    def peek(self):
        if len(self) == 0:
            raise IndexError("You cannot peek into an empty stack.")

        return self._stack[len(self) - 1]

    def push(self, item):
        self._stack.append(item)

    def __iter__(self):
        return iter(self._stack)
If you don't care if the error is textually correct, then you can remove the if in pop and peek.
You don't need to find the length of the stack to find the last element. You can just use self._stack[-1].


Creating:

class Stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def pop(self):
        return self._stack.pop()

    def peek(self):
        return self._stack[-1]

    def push(self, item):
        self._stack.append(item)

    def __iter__(self):
        return iter(self._stack)


From this, it begs the question why not inherit from list? Which would make the code:

class Stack(list):
    def peek(self):
        return self[-1]

    def push(self, item):
        self.append(item)


If you're likely to switch to another form of Stack, then you may want to keep with this. However, for the most part I'd recommend not using this class. As the only benefit it has over list is that it's likely to work with more Stack interfaces.