A stack adds and removes elements at the same end. The last element added is the first removed, so a stack is first-in, last-out. section 26.4
Picture a stack of pancakes: put new pancakes on top and take pancakes from the top. With a Python list, the end of the list acts as the top; append() adds an element and pop() removes it. section 26.4
Listing 32.1. Definition for the Stack class
class Stack(object):
def __init__( self):
self.stack = [] #1
def get_stack_elements(self):
return self.stack.copy() #2
def add_one(self , item):
self.stack.append(item) #3
def add_many(self , item, n):
for i in range(n): #4
self.stack.append(item) #4
def remove_one(self):
self.stack.pop() #5
def remove_many(self , n):
for i in range(n): #6
self.stack.pop() #6
def size(self):
return len(self.stack) #7
def prettyprint(self):
for thing in self.stack[::-1]: #8
print('|_',thing, '_|') #8
A Stack class packages list-backed operations such as adding and removing one or several items. section 32.1
Pancakes and circles
Add blueberry and chocolate pancakes, then remove one to take the most recently added pancake. The same Stack class can also hold Circle objects. section 26.4 section 32.2













