Use List as Stack (LIFO)¶
Zero-dependency Python snippets for using a list as a stack (Last-In, First-Out) with the standard library.
4 snippets available in this sub-category.
Simple¶
Push and pop with list¶
stack
list
push
pop
LIFO
data-structures
Use list append() and pop() for stack operations
stack = []
stack.append(1) # Push
stack.append(2)
stack.append(3)
print(stack) # [1, 2, 3]
item = stack.pop() # Pop
print(item) # 3
print(stack) # [1, 2]
Notes
- append() adds to the end (top of stack)
- pop() removes from the end (top of stack)
Peek at top of stack¶
stack
peek
list
data-structures
Access the top element without removing it
Notes
- Use stack[-1] to peek at the top
- Raises IndexError if stack is empty
Complex¶
Stack with error handling¶
stack
error-handling
safe
data-structures
Safe pop with empty stack check
def safe_pop(stack):
if stack:
return stack.pop()
else:
print("Stack is empty!")
return None
stack = []
safe_pop(stack) # Prints warning, returns None
Notes
- Always check if stack is not empty before popping
Stack size and clear¶
stack
size
clear
list
data-structures
Get stack size and clear stack
Notes
- len(stack) for size, clear() to empty
🔗 Cross Reference¶
- Reference: See 📂 Use deque as Queue
🏷️ Tags¶
stack
, list
, push
, pop
, peek
, size
, clear
, LIFO
, data-structures
📝 Notes¶
- Python lists are efficient for stack operations
- For thread-safe or multi-producer/consumer stacks, use queue.LifoQueue