I'm learning Python by implementing commonly used data structures. My primary language is Java, thus would like to know if I'm being Pythonic enough. Any means to better up will be appreciated.

class Node:
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

from node import Node

class Stack:
    def __init__(self):
        self.top = None
        self.size = 0

    def push(self, item):
        curr = Node(item)
        self.size += 1
        if self.top is None:
            self.top = curr
            curr.next = self.top
            self.top = curr

    def peek(self):
        return self.top.value

    def pop(self):
        if self.top is None:
            raise Exception("Nothing to pop.")
        curr = self.top
        self.top = self.top.next
        self.size -= 1
        return curr

    def __sizeof__(self):
        return self.size

    def is_empty(self):
        return self.size == 0;

    def __str__(self):
        curr = self.top
        while curr:
            print(curr.value, end=' ')
            curr = curr.next

1 Answer 1


The easiest way to create Stack that I found was this:

class Stack:
    def __init__(self):
        self.stack = []
    def push(self,data):
    def pop(self):
        if self.isEmpty():
            raise Exception("nothing to pop")
        return self.stack.pop(len(self.stack)-1)
    def peek(self):
        if self.isEmpty():
            raise Exception("Nothing to peek")
        return self.stack[len(self.stack)-1]
    def __sizeOf__(self):
        return len(self.stack)
    def isEmpty(self):
        return len(self.stack) == 0
    def __str__(self):
        for x in self.stack.reverse(): #Reverse list, so when printing last pushed value is first and the oldest is printed last.

What it does is when creating Stack Variable:

  • it makes new list called stack.
  • When you push something to Stack, it is added at the end of list.
  • When you pop something from Stack, it is taken away form list (method pop() will not only return value from list, but also delete it)
  • When you peek something from Stack, it returns last value on list without deleting it.
  • When you want to check size of stack, it measures list size.
  • When you want to use __str__ you print all variables from list.

I have reversed the list using for x in stack:. This was done because otherwise x would be equivalent to stack[0] in first run, stack[1] in second etc. However we must not forget that stack[0] is the oldest value placed in stack, and the newest is the value with the highest index in list. Reversing the list allows to print from the newest value to the oldest.

A little bit more of explanation:

  • self.stack.pop(len(self.stack)-1) - This code will pop last value from list. It contains -1 because length of stack is started from 1 while indexing is started from 0. Function len() returns (in this case) length of list

  • if self.isEmpty(): raise Exception("Nothing to peek") - This code will run its function isEmpty() from its own class, which returns Boolean value (which is perfect for our if statement).

  • self.stack[len(self.stack)-1] while using list you will use list name (in this case stack) and then index you want to access, e.g. stack[1] (will return second value in list, dont forget about 0-indexing).

  • \$\begingroup\$ __sizeOf__ should be __sizeof__, unless you're implementing your own magic methods on purpose (in which case, don't). But really, it should return sys.sizeof(self.stack); In most cases, len(obj) != sys.sizeof(obj)! \$\endgroup\$
    – Daniel
    Apr 8, 2018 at 21:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.