Stack using Array in Python
Implementation of Stack Using Array in Python
Stack using Array in Python is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle.
Stacks are fundamental data structures in computer science, widely used for various applications. We will provide a comprehensive guide on creating a stack using array in python, covering the key concepts and operations involved.
Implementation of Stack using Array in Python
An array implementation of a stack is a way to create a stack data structure using a one-dimensional array or list in a programming language. In this implementation, the array is used to store the elements of the stack, and the stack operations (push, pop, peek, etc.) are performed using the array’s operations.
Array-Based Stack Implementation
Now, let’s delve into the core of our topic: implementing a stack using arrays.
class Stack: def __init__(self, capacity): self.capacity = capacity self.stack = [None] * capacity self.top = -1
def push(self, item): if self.top == self.capacity - 1: print("Stack Overflow") return self.top += 1 self.stack[self.top] = item
def pop(self): if self.top == -1: print("Stack Underflow") return None item = self.stack[self.top] self.top -= 1 return item
Example: Implementation of Stack using Array in Python
class Stack: def __init__(self): self.stack = [] def is_empty(self): return len(self.stack) == 0 def push(self, item): self.stack.append(item) def pop(self): if not self.is_empty(): return self.stack.pop() else: print("Stack is empty. Cannot pop.") return None def peek(self): if not self.is_empty(): return self.stack[-1] else: print("Stack is empty. Cannot peek.") return None def size(self): return len(self.stack) # Example usage: stack = Stack() stack.push(1) stack.push(2) stack.push(3) print("Stack:", stack.stack) # Output: Stack: [1, 2, 3] print("Peek:", stack.peek()) # Output: Peek: 3 print("Pop:", stack.pop()) # Output: Pop: 3 print("Stack:", stack.stack) # Output: Stack: [1, 2] print("Is Empty?", stack.is_empty()) # Output: Is Empty? False print("Stack Size:", stack.size()) # Output: Stack Size: 2
Advantages of Array-Based Stack
- Implementing a stack using arrays offers several advantages:
Conclusion
In conclusion, Stack using Array in Python data structure is a fundamental concept in computer science and programming. Its implementation can vary, but the core principles of push, pop, and LIFO remain consistent. Understanding stacks and their applications is crucial for any programmer or computer scientist.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others