Python Program to Append, Delete and Display Elements of a List Using Classes

In this example, we will write a python program to append, delete and display elements of a list usign classes. To better understand this example, make sure you have knowledge of the following tutorials:-

Python Program to Convert temperatures using Classes

class MyList:
    def __init__(self):
        self.n = []

    def add(self, a):
        return self.n.append(a)

    def remove(self, b):
        self.n.remove(b)

    def display(self):
        return (self.n)


obj = MyList()

choice = 1
while choice != 0:
    print("0. Exit")
    print("1. Add")
    print("2. Delete")
    print("3. Display")
    choice = int(input("Enter choice: "))
    if choice == 1:
        n = int(input("Enter number to append: "))
        obj.add(n)
        print("List: ", obj.display())

    elif choice == 2:
        n = int(input("Enter number to remove: "))
        obj.remove(n)
        print("List: ", obj.display())

    elif choice == 3:
        print("List: ", obj.display())
    elif choice == 0:
        print("Exiting!")
    else:
        print("Invalid choice!!")

The output of the above program is:-

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 20
List: [20]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 30
List: [20, 30]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
Enter number to remove: 30
List: [20]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 3
List: [20]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!
Program Explanation
  • A class named “MyList” is defined that has three methods add, remove and display
  • The choice menu is shown for the user to select the option.
  • A while loop is used to loop through the choices
  • An object of the MyList class is created and called as the user chooses the option
  • The values in the list are displayed when any action is performed.
SHARE Python Program to Append, Delete and Display Elements of a List Using Classes

You may also like...

Leave a Reply

Your email address will not be published.

Share