Python Program for a Menu-Driven List
Intermediate · Lists · CBSE class 12 practical list
A menu-driven program shows numbered options, runs the one the user picks and comes back to the menu until the user chooses Exit. This program offers add, remove, sort, search and display operations on a list of numbers, a common CBSE practical question on lists.
Program
Menu: 1.Add 2.Remove 3.Sort 4.Search 5.Display 6.Exit Choice 5: the list is [25, 10, 40] Choice 1: added 30 Choice 2: removed 10 Choice 2: 99 is not in the list Choice 3: list sorted Choice 4: 40 found at index 2 Choice 4: 7 not found Choice 8: invalid choice Choice 5: the list is [25, 30, 40] Choice 6: exiting the menu
How it works
- The
stepslist plays the part of the user: each pair is a menu choice and the number that goes with it. - The
if/elifchain runs a different list operation for each choice:append(),remove(),sort(),index()and printing the list. - Remove and search check
value in numbersfirst, becauseremove()andindex()raise aValueErrorfor a value that is not in the list. - Choice 6 ends the loop with
break, and a number outside 1 to 6, like 8, gets an invalid choice message. - In the
input()version,while True:repeats the menu again and again, andbreakon choice 6 is the only way out.
Another way to write it
With a while loop, like the input() version
List: [5, 3, 8] Sum: 16 Reversed: [8, 3, 5] Largest: 8 Bye
This is the shape a practical file needs: while True keeps showing the menu and only the exit choice breaks out. Replace typed.pop(0) with the input() call from the comment to make it interactive.
Try it yourself
Add a choice 7 that puts a number at the start of the list with numbers.insert(0, value), and add a step that uses it.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Search for an Element in a List
- Find the Largest and Smallest Number in a List
- Implement a Stack Using a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- Find the Sum of Elements in a List
- Reverse a List
- Count Occurrences of an Element in a List
All Python programs · CBSE class 12 practical file · Python exercises