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.items
which will be used to store the elements of the stack.
- Initializes an empty list
Push operation (
push
method):- Appends (
pushes
) an item to the end of the list (self.items
).
- Appends (
Pop operation (
pop
method):- Removes and returns the last item from
self.items
if the stack is not empty. If the stack is empty, it raises anIndexError
.
- Removes and returns the last item from
Peek operation (
peek
method):- Returns the last item from
self.items
without 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.items
is empty and returnsTrue
if it is,False
otherwise.
- 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