CP164 Final: The Array
The Array-Based Stack Implementation
Pushing Items Onto an Array-Based Stack
def push(self, value):
"""
-------------------------------------------------------
Pushes a copy of value onto the top of the stack.
Use: stack.push(value)
-------------------------------------------------------
Parameters:
value - value to be added to stack (?)
Returns:
None
-------------------------------------------------------
"""
self._values.append(deepcopy(value))
return
push simply uses the Python list method append to add value to the end of the _values list.
Note, however, the use of the deepcopy method. copy is a Python library, and deepcopy is
one of its methods. deepcopy returns a complete copy of whatever is passed to it. (Using
the copy library requires an import copy statement at the top of the module.) It is
important to understand what happens if we don't use it. The following code shows the
creation of a student object:
student = Student("013412060", "Brown", "David", ...)
This object is then pushed onto a stack:
stack.push(student)
Document Summary
Pushing items onto an array-based stack def push(self, value): Pushes a copy of value onto the top of the stack. Parameters: value - value to be added to stack (?) None self. _values. append(deepcopy(value)) return push simply uses the python list method append to add value to the end of the _values list. It is important to understand what happens if we don"t use it. The following code shows the creation of a student object: student = student(013412060, brown, david, ) This object is then pushed onto a stack: stack. push(student) Changing the contents of student then changes the contents of the student object stored in the stack, because both student and the stack object point to the same location in memory. Using deepcopy makes a copy of the student object in the stack, so that student and the object in the stack point to different memory locations, as in this diagram: