Implementing a Stack in Python

Tl;dr #

  • Use .append() and pop() together for traditional stack (most common usage)
  • Use insert(0, item) and pop() if you want a LIFO stack

Stack #

Stacks can be implemented using a set() or a list().

Both allow some sort of enque method and a list.pop()/set.pop() as deque methods.

List implementation #

To implement it using a list,

my_stack = []

# Push
my_stack.append('a')
# >> ['a']
my_stack.append('b')
# >> ['a', 'b']
my_stack.append('c')
# >> ['a', 'b', 'c']

# Pop
my_stack.pop()
# Returns 'c' (last item appended)
# my_stack: ['a', 'b']
my_stack.pop()
# Returns 'b' (2nd item appended)
# my_stack: ['a']
my_stack.pop()
# Returns 'a' (1st item appended)
#  my_stack: []

The python pop() method on a list, removes the last item of the list and returns it to you.

[1, 2, 3, 4, 5, 6, 7, 8, 9].pop()
#                        Λ
#           _____________|
#          |
# 9 is removed and returned 
# when you call a pop()!

May 17, 2020