I Built Stack Data Structure in Python (3 mins guide)

Veröffentlicht am: 08 Januar 2025
auf dem Kanal: CodeToCompass
97
4

stack data structure in python | stack data structure using linked list | stack data structure in one video | stack in python code | stack in python dsa


🧠 Learn Stacks in Python in 3-Minutes!

A stack is a simple data structure that works like a pile of plates: LIFO (Last In, First Out). Let’s build one from scratch in Python using a class! 🎉


📦 1. Create a Stack Class
class Stack:
def __init__(self):
self.items = [] # Use a list to hold stack elements

📥 Push: Add an item to the stack
def push(self, item):
self.items.append(item)

📤 Pop: Remove and return the top item
def pop(self):
if not self.is_empty():
return self.items.pop()
return "Stack is empty!"

👀 Peek: Look at the top item without removing it
def peek(self):
if not self.is_empty():
return self.items[-1]
return "Stack is empty!"

❓ Is Empty: Check if the stack is empty
def is_empty(self):
return len(self.items) == 0

📏 Size: Check the size of the stack
def size(self):
return len(self.items)

🛠️ 2. Use the Stack
stack = Stack() # Create a stack
stack.push(1) # Add 1
stack.push(2) # Add 2
print(stack.peek()) # Peek: 2️⃣
print(stack.pop()) # Pop: 2️⃣
print(stack.size()) # Size: 1️⃣

💡 Why Use a Stack?

Undo/redo operations 📝
Backtracking algorithms 🧩
Expression evaluation 📜

🔑 Key Takeaway: Stacks are super easy to implement in Python and incredibly useful in programming!

Like this video? Please subscribe to my channel, and don't forget to check out my link tree!

https://linktr.ee/code2compass


Auf dieser Seite können Sie das Online-Video I Built Stack Data Structure in Python (3 mins guide) mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer CodeToCompass 08 Januar 2025 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 97 Mal angesehen und es wurde von 4 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!