How to Implement a Stack in Python


In this example, we will learn how to implement a stack in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

class Stack(object):
    # initialize stack by creating a empty list
    def __init__(self):
        self.items = []

    # Determine if the stack is empty, return a boolean value
    def is_empty(self):
        return self.items == []

    # Return to the top element of the stack
    def peek(self):
        return self.items[len(self.items) - 1]

    # Return the size of the stack
    def size(self):
        return len(self.items)

    # Push into the stack
    def push(self, item):
        self.items.append(item)

    # pop stack
    def pop(self):
        return self.items.pop()


# Start to test the stack
TestStack = Stack()

# push 'Boston' into stack
TestStack.push('Boston')

# push 'New York' int stack
TestStack.push('New York')

# push a number of 23 int stack
TestStack.push(23)

print('Stack Size: ' + TestStack.size())
print ('Start Popup items in stack')

# pop all
while TestStack.size()>0:
    print(TestStack.peek())
    TestStack.pop()

print('Is the stack empty now? ', TestStack.is_empty())

Output:

Stack Size: 3
23
New York
Boston
Is the stack empty now? True
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments