HomePythonPython Program to Append, Delete and Display Elements of a List using Classes

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

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:

  1. We define a class named CustomList with three methods: append_element, delete_element, and display_elements.
  2. The __init__ method initializes an empty list data when an instance of the class is created.
  3. The append_element method takes an element as an argument and appends it to the data list.
  4. The delete_element method takes an element as an argument, checks if it exists in the data list, and removes it if found.
  5. The display_elements method simply prints the elements of the data list.
  6. We create an instance of the CustomList class called my_list.
  7. We append three elements to the list using the append_element method.
  8. We display the elements of the list using the display_elements method.
  9. We delete an element using the delete_element method.
  10. We again display the updated elements of the list.

Input/Output:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...