Code:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def length(stack):
i = 0
while not stack.is_empty():
stack.pop()
i += 1
return i
s1 = Stack()
s1.push(3)
s1.push(2)
s1.push(1)
print(length(s1))
s1.pop()
Output:
3
Traceback (most recent call last):
File "Stack.py", line 26, in <module>
s1.pop()
File "Stack.py", line 12, in pop
return self.items.pop()
IndexError: pop from empty list
I want the function length()
to be able to modify a copy of s1
instead on changing s1
. Is there any way to do this in python?
I am not allowed to directly use s1.items
so I can't just use s1[:]
. I can't modify the class either.