Here's a simple implementation of a stack data structure in Python using a list:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
Explanation:
Initialization (
__init__method):- Initializes an empty list
self.itemswhich will be used to store the elements of the stack.
- Initializes an empty list
Push operation (
pushmethod):- Appends (
pushes) an item to the end of the list (self.items).
- Appends (
Pop operation (
popmethod):- Removes and returns the last item from
self.itemsif the stack is not empty. If the stack is empty, it raises anIndexError.
- Removes and returns the last item from
Peek operation (
peekmethod):- Returns the last item from
self.itemswithout removing it, if the stack is not empty. If the stack is empty, it returnsNone.
- Returns the last item from
is_empty method:
- Checks if
self.itemsis empty and returnsTrueif it is,Falseotherwise.
- Checks if
size method:
- Returns the number of elements currently in the stack (
len(self.items)).
- Returns the number of elements currently in the stack (
Example Usage:
push, pop, and peek) commonly used in stack data structures. Adjustments can be made depending on specific requirements or constraints of the problem at hand.Tags: Implement a stack data structure with push pop and peek operations in Python Interview Questions Answer freshers experienced level advanced programs

