implementation of stack in python code example
Example 1: best python stack implementation
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
Example 2: stack data structure python
from collections import deque
myStack = deque()
myStack.append('a')
myStack.append('b')
myStack.append('c')
myStack
deque(['a', 'b', 'c'])
myStack.pop()
'c'
myStack.pop()
'b'
myStack.pop()
'a'
myStack.pop()
Example 3: python stack data structure
>>> from collections import deque
>>> myStack = deque()
>>> myStack.append('a')
>>> myStack.append('b')
>>> myStack.append('c')
>>> myStack
deque(['a', 'b', 'c'])
>>> myStack.pop()
'c'
>>> myStack
deque(['a', 'b'])
Example 4: stack in python
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self, x):
return (self.data.count(x))
def my_show_all(self):
return (self.data)
arrStack = My_stack()
arrStack.my_push(1)
arrStack.my_push(2)
arrStack.my_push(1)
arrStack.my_push(3)
print(arrStack.my_show_all())
arrStack.my_pop()
print(arrStack.my_show_all())
print(arrStack.my_contains(1))
Example 5: stack example in python
>>> myStack = []
>>> myStack.append('a')
>>> myStack.append('b')
>>> myStack.append('c')
>>> myStack
['a', 'b', 'c']
>>> myStack.pop()
'c'
>>> myStack.pop()
'b'
>>> myStack.pop()
'a'
>>> myStack.pop()
Traceback (most recent call last):
File "<console>", line 1, in <module>
IndexError: pop from empty list