Jul 17, 2024
data.append(element)
element = data.pop()
element = data[len(data) - 1]
data = []
data.append(5)
element = data.pop()
print(element) # Output: 5
print(data) # Output: []
append
and pop
to maintain stack integrity.element = data[len(data) - 1]
data.append(element)
element = data.pop(0)
element = data[0]
data = []
data.append(5)
data.append(10)
element = data.pop(0)
print(element) # Output: 5
print(data) # Output: [10]
element = data.pop(0)
element = data[0]
deque
from collections
from collections import deque
data.append(element)
element = data.popleft()
from collections import deque
data = deque()
data.append('Caleb')
element = data.popleft()
print(element) # Output: Caleb
print(data) # Output: deque([])
class Stack:
def __init__(self):
self._data = []
def push(self, data):
self._data.append(data)
def pop(self):
return self._data.pop()
def peek(self):
return self._data[len(self._data) - 1]
stack = Stack()
stack.push(10)
print(stack.peek()) # Output: 10
print(stack.pop()) # Output: 10
Next Steps: Continue to practice with hands-on examples and build a deeper understanding of data structures.