Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
Stack Implementation using List
AIM
To write a Python program to implement stack data structure using list with push, pop, and display operations.
ALGORITHM
- Start
- Initialize an empty list as stack
- Define push() function to add elements to stack
- Define pop() function to remove elements from stack
- Define display() function to show stack contents
- Create menu-driven interface
- Perform operations based on user choice
- Stop
PROGRAM
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
"""Add an element to the top of stack"""
self.stack.append(item)
print(f"Pushed {item} to stack")
def pop(self):
"""Remove and return the top element from stack"""
if self.is_empty():
print("Stack is empty! Cannot pop.")
return None
else:
item = self.stack.pop()
print(f"Popped {item} from stack")
return item
def peek(self):
"""Return the top element without removing it"""
if self.is_empty():
print("Stack is empty!")
return None
else:
return self.stack[-1]
def is_empty(self):
"""Check if stack is empty"""
return len(self.stack) == 0
def size(self):
"""Return the size of stack"""
return len(self.stack)
def display(self):
"""Display all elements in stack"""
if self.is_empty():
print("Stack is empty!")
else:
print("Stack contents (top to bottom):")
for i in range(len(self.stack) - 1, -1, -1):
print(f"| {self.stack[i]} |")
print("+---+")
def main():
stack = Stack()
while True:
print("\n--- Stack Operations ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Size")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
item = input("Enter element to push: ")
stack.push(item)
elif choice == '2':
stack.pop()
elif choice == '3':
top = stack.peek()
if top is not None:
print(f"Top element: {top}")
elif choice == '4':
stack.display()
elif choice == '5':
print(f"Stack size: {stack.size()}")
elif choice == '6':
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()OUTPUT
--- Stack Operations ---
1. Push
2. Pop
3. Peek
4. Display
5. Size
6. Exit
Enter your choice (1-6): 1
Enter element to push: 10
Pushed 10 to stack
Enter your choice (1-6): 4
Stack contents (top to bottom):
| 10 |
+---+
CONCLUSION
Thus, the stack data structure was successfully implemented using Python list with all basic operations.
VIVA QUESTIONS
What is a stack data structure?
A stack is a linear data structure that follows LIFO (Last In First Out) principle.
What are the main operations of a stack?
Push (insert), Pop (delete), Peek/Top (view top element), isEmpty, and Size.
What is stack overflow and underflow?
Overflow occurs when pushing to a full stack, underflow occurs when popping from an empty stack.