educative.io

How to calculate the size of the stack?

how do I write a method to calculate the length of the stack? How do I use the len() for it?

I have written
def len_of(self):
x= len(self.items)
return x
is there something wrong with it syntactically? Can i write it any better? the use of the the inbuilt function len() is what I am concerned about

No, it’s perfectly fine you can calculate the length of stack like this. In case you don’t want to use the len() function you can iterate a loop and start poping the elements one by one and set counter till stack is not empty. It’s the other approach that you can use.