educative.io

Educative

Why can't we just use len(self.stack_list) to get the size of the stack?

the above intro keeps an integer variable counter to track the size as it pushes and pops, but why can’t we just use len() to get the size like this?

class MyStack:

    def __init__(self):
        self.stack_list = []
    def is_empty(self):
        if self.stack_list == []:
            return True
    def peek(self):
        if self.is_empty():
            return None
        return self.stack_list[len(self.stack_list)-1]
    def size(self):
        return len(self.stack_list)
    def push(self, value):
        self.stack_list.append(value)
    def pop(self):
        return self.stack_list.pop()

We can use len() function as well. To make learners’ understand that how push() and pop() work we kept a separate variable of size. Moreover, this len() function works in Python only so to build a generic concept self.stack_size variable is mentioned.