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

PythonServer Side ProgrammingProgramming

When it is required to append, delete, and display the elements of a list using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to add elements to the list, delete elements from the list and display the elements of the list using objects.

Below is a demonstration for the same −

Example

 Live Demo

class list_class():
   def __init__(self):
      self.n=[]
   def add_val(self,a):
      return self.n.append(a)
   def remove_val(self,b):
      self.n.remove(b)
   def display_val(self):
      return (self.n)
my_instance = list_class()
choice_val = 1
while choice_val!=0:
   print("0. Exit")
   print("1. Add elements")
   print("2. Delete element")
   print("3. Display list")
   choice_val=int(input("Enter your choice: "))
   if choice_val==1:
      n=int(input("Enter element to add to the list... "))
      my_instance.add_val(n)
      print("List: ",my_instance.display_val())
   elif choice_val==2:
      n=int(input("Enter number to delete.."))
      my_instance.remove_val(n)
      print("List: ",my_instance.display_val())
   elif choice_val==3:
      print("List: ",my_instance.display_val())
   elif choice_val==0:
      print("Exit")
   else:
      print("Invalid choice!")
print()

Output

0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 1
Enter element to add to the list... 34
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 3
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 2
Enter number to delete..34
List: []
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 0
Exit

Explanation

  • A class named ‘list_class’ class is defined, that has functions like ‘add_val’, ‘remove_val’, and ‘display_val’.
  • These are used to add elements to the list, remove element from the list and display the list respectively. An instance of this class is created.
  • The elements of the list are entered and operations are performed on it.
  • Relevant messages and output is displayed on the console.
raja
Published on 11-Mar-2021 12:54:38
Advertisements