How to implement Stack in python

0 votes

I have 2 issues with the code below:

  1. push(o) throws an exception TypeError: can only assign an iterable.
  2. Should I throw an exception if pop() is invoked on an empty stack ?

    class Stack(object):
    
        def __init__(self):
            self.storage = []
    
        def isEmpty(self):
            return len(self.storage) == 0
    
        def push(self,p):
            self.storage[:0] = p
    
        def pop(self):
            """issue: throw exception?"""
            return None

Nov 15, 2018 in Python by Jino
• 5,520 points
19 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
class Stack:
  def __init__(self):
    self.__storage = []

  def isEmpty(self):
    return len(self.__storage) == 0

  def push(self,p):
    self.__storage.append(p)

  def pop(self):
    return self.__storage.pop()

This way you can securely implement all the functions of stack.

answered Nov 15, 2018 by findingbugs
• 3,140 points

Related Questions In Python

0 votes
1 answer

How to implement Hashmaps in Python

Python dictionary is a built-in type that supports ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,710 points
84 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 56,140 points
37 views
0 votes
1 answer

How to implement Linked List in Python?

You can use Deque that works better than linked list ...READ MORE

answered Oct 26, 2018 in Python by Priyaj
• 56,140 points
26 views
0 votes
1 answer

How to implement Queue in python

You are missing this  from queue import * This ...READ MORE

answered Nov 2, 2018 in Python by Nabarupa
45 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
55 views
+4 votes
6 answers
0 votes
1 answer

How to write to CSV line by line in python

The simple way of doing this will ...READ MORE

answered Nov 15, 2018 in Python by findingbugs
• 3,140 points
107 views
0 votes
1 answer

How to do Matrix Multiplication in python?

def matmult(a,b): zip_b = ...READ MORE

answered Nov 15, 2018 in Python by findingbugs
• 3,140 points
165 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.