All Courses

How to implement stack in python using list?

By Neha, 2 years ago
  • Bookmark
0

Implement stack using list methods

Stack
List
Python
1 Answer
0

Implementation of stack :

The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below.

  • Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack.
  • push(item) adds a new item to the top of the stack. It needs the item and returns nothing.
  • pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified.
  • peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified.
  • isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value.
  • size() returns the number of items on the stack. It needs no parameters and returns an integer.
  • print() return items in the stack.It needs no parameters and returns a list.


class Stack(object):
   
        def __init__(self):        
            self.items = []
           
        def isEmpty(self):          # Check Stack is Empty or not return True or False
            return self.items == []
         
        def push(self, item):        # Insert/push Element in stack
            self.items.append(item)      
           
        def pop(self):            # Delete/pop element from stack
            return self.items.pop()
         
        def peek(self):           # Top of the stack
            return self.items[len(self.items)-1]
         
        def size(self):           # Size of Stack
            return len(self.items)
           
        def print(self):           # Print stack
            return self.items


 

In   [47]:s = Stack()

 

In   [49]: s.push(1)
           s.push(2)
           s.push(3)
           s.push('a')
           s.push(-2)


In   [50]: s.print()
Out[50]: [1, 2, 3, 1, 2, 3, 'a', -2]

 

In   [51]: s.pop()
Out[50]: -2

 

In   [52]: s.print()
Out[50]: [1, 2, 3, 1, 2, 3, 'a']

 

In   [53]: s.peek()
Out[50]: a

 

In   [54]: s.size()
Out[50]: 7

 

In   [55]: s.isEmpty()
Out[50]: False


Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Jun 1st (5:32 PM) 515 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More