Back

Implementing a stack in Python

Introduction
A stack can be implemented in Python easily using lists and list methods. There are broadly two approaches that can be used. We can simply create the functions we need, or if we are using an Objected Oriented approach, we can create a class and use that. In both cases, we could put the code into our own library. That way, when we need a stack in the future, we don't have to rewrite the code and test it. We just import the library and use the stack.

Creating a stack using functions
Here is some code to create a stack and the functions needed to display the contents, pushing and popping items and testing it to see if it is empty.

functions

When you run the code, you can see that because we are using a list, we can hold a mixture of data types and structures.

Creating a library of functions
Stacks are useful data structures. We can store these functions in our own library, and use them in the future rather than rewriting them whenever we need one. We need to remove everything except the functions from our code above. We also need to ensure that we can pass the stack name and size we are using from our main program to the library functions. The library functions must be generic; they must work with any stack name and any stack size. Store the following as a file called my_library.py .

functions lib 

Using the library
To use an existing library of functions, you need to import the library into your new program. The simplest way to do this is to make sure that the library is in the same folder as your new program. Here is an example of using the library we just created:

functions lib use

As you can see, we imported the library in our main program and then created a new stack and specified its size. These parameters were then passed to the functions in the library using the dot notation, the library name followed by a dot and then name of the function, along with any parameters needed.

Using an Object Oriented approach
If you are using an OO approach in Python, we can create a class called Stack in a library. We can then import and use that when we need to in another program. Again, make sure the library (which we will call stack1.py) and main program are in the same folder. Here is the code for the class, which is stored in the library:

oo 1

Here is an example program that uses the class in the library.

oo 2

Tasks
Q1. Make sure you get the code running for creating a stack, and using a stack in a library.
Q2. Test the stack and its different functions, by pushing and popping data, predicting the results and then displaying the contents of the stack.
Q3. Investigate how you would import a library if it wasn't in the same folder as the program that used the library.
Q4. It can be a little bit tedious and time-consuming having to use the dot notation and typing in long library names and long function names. Investigate how you could reduce this problem.

Back