Shankar
Shankar

Reputation: 3624

Ambiguous behavior of using "not" and "bool" together on an empty list in Python

In this simple implementation of Stack using Python lists. I have a small method to check if the stack is empty (list empty). I am using this method as a check condition for pop method. The pop method should raise an exception when trying to pop an empty stack. For some reason, this doesn't seem to work. Am I missing something here? Please help!

 __author__ = '@arun'
# Stack simple implementation using Python list


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

    def push(self, value):
        self.items.append(value)

    def is_empty(self):
        return not bool(self.items)

    def pop(self):
        print self.is_empty()
        if self.is_empty:  # if not stack is empty
            return self.items.pop()
        else:
            raise Exception("Stack Empty!")

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

    def get_size(self):
        return len(self.items)

if __name__ == '__main__':
    stack = Stack()
    print stack.get_size()
    stack.push(23)
    stack.push(3)
    print stack.get_size()
    print stack.pop()
    print stack.pop()
    print stack.get_size()
    #print stack.pop()

Output:

0
2
False
3
False
23
0

Why is pop() method popping out elements when is_empty() is returning False?!

Upvotes: 1

Views: 257

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

if self.is_empty:

will always evaluate to True, since it is a Truthy value. You need to call the function like this

if self.is_empty():

And a suggestion: You might want to pop the values only when is_empty() is False, like this

if not self.is_empty():

Upvotes: 8

Related Questions