5.11 Simulating Stacks with Lists

  • Python does not have a built-in stack type.
  • Can think of a stack as a constrained list.
  • Push using list method append.
  • Pop using list method pop with no arguments to get items in last-in, first-out (LIFO) order.
In [1]:
stack = []
In [2]:
stack.append('red')
In [3]:
stack
Out[3]:
['red']
In [4]:
stack.append('green')
In [5]:
stack
Out[5]:
['red', 'green']
In [6]:
stack.pop()
Out[6]:
'green'
In [7]:
stack
Out[7]:
['red']
In [8]:
stack.pop()
Out[8]:
'red'
In [9]:
stack
Out[9]:
[]
In [10]:
stack.pop()
------------------------------------------------------------------------
IndexError                             Traceback (most recent call last)
<ipython-input-10-415460d3b717> in <module>
----> 1 stack.pop()

IndexError: pop from empty list
  • Also can use a list to simulate a queue.
  • Items are retrieved from queues in first-in, first-out (FIFO) order.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.