In this Python program, we’ll create a class that represents a list. The class will have methods to append elements, delete elements, and display the elements of the list. This program demonstrates the use of classes and methods to manipulate a list-like data structure.
Problem Statement:
Create a Python program that defines a class CustomList. This class should have methods to append elements to the list, delete elements from the list, and display the elements of the list.
Python Program to Append, Delete and Display Elements of a List using Classes
class CustomList:
def __init__(self):
self.data = []
def append_element(self, element):
self.data.append(element)
def delete_element(self, element):
if element in self.data:
self.data.remove(element)
else:
print(f"{element} not found in the list.")
def display_elements(self):
print("List Elements:", self.data)
# Create an instance of the CustomList class
my_list = CustomList()
# Append elements to the list
my_list.append_element(10)
my_list.append_element(20)
my_list.append_element(30)
# Display the initial list elements
my_list.display_elements()
# Delete an element from the list
my_list.delete_element(20)
# Display the updated list elements
my_list.display_elements()
How it Works:
- We define a class named
CustomListwith three methods:append_element,delete_element, anddisplay_elements. - The
__init__method initializes an empty listdatawhen an instance of the class is created. - The
append_elementmethod takes an element as an argument and appends it to thedatalist. - The
delete_elementmethod takes an element as an argument, checks if it exists in thedatalist, and removes it if found. - The
display_elementsmethod simply prints the elements of thedatalist. - We create an instance of the
CustomListclass calledmy_list. - We append three elements to the list using the
append_elementmethod. - We display the elements of the list using the
display_elementsmethod. - We delete an element using the
delete_elementmethod. - We again display the updated elements of the list.
Input/Output:
