Python stack

Share me please

Stack build from Python lists

[cc lang=”python”]
# initialize stack as a list
stack1 = []

# stack is linear structure with defined rule last in firt out (LIFO)
stack1.append(“first element”)
stack1.append(“second element”)
stack1.append(“third element”)
stack1.append(“fourth element”)
print(stack1)

# get last element from the stack
elem = stack1.pop()
print(elem)
print(stack1)

# get last element from the stack
elem = stack1.pop()
print(elem)
print(stack1)
[/cc]

Stack built from deque collection

[cc lang=”python” height=”390px”]
from collections import deque

# initialize stack
stack1 = deque()

# stack is linear structure with defined rule last in firt out (LIFO)
stack1.append(“first element”)
stack1.append(“second element”)
stack1.append(“third element”)
stack1.append(“fourth element”)
print(stack1)

# get first element from the stack
elem = stack1.pop()
print(elem)
print(stack1)

# get next first element from the stack
elem = stack1.pop()
print(elem)
print(stack1)
[/cc]

Stack built from lifo queue

[cc lang=”python” height=”580px”]
from queue import LifoQueue

# initialize stack
stack1 = LifoQueue()

# stack is linear structure with defined rule first in last in firt out (LIFO)
stack1.put(“first element”)
stack1.put(“second element”)
stack1.put(“third element”)
stack1.put(“fourth element”)
print(stack1)

# get first element from the stack
elem = stack1.get()
print(elem)
print(stack1)

# get next first element from the stack
elem = stack1.get()
print(elem)
print(stack1)

# current number of elements in a stack
print( stack1.qsize())

# maximum size of elements in a stack
print( stack1.maxsize)

# check if stack1 is empty
print( stack1.empty() )

# check if stack1 is full
print( stack1.full() )

[/cc]