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

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 ?

Class Definition

First, let's define a class that encapsulates list operations ?

class ListManager:
    def __init__(self):
        self.items = []
    
    def add_element(self, element):
        """Add an element to the list"""
        self.items.append(element)
        return self.items
    
    def remove_element(self, element):
        """Remove an element from the list"""
        if element in self.items:
            self.items.remove(element)
            return True
        return False
    
    def display_list(self):
        """Display the current list"""
        return self.items
    
    def is_empty(self):
        """Check if list is empty"""
        return len(self.items) == 0

Complete Interactive Example

Here's a complete program demonstrating list operations using the class ?

class ListManager:
    def __init__(self):
        self.items = []
    
    def add_element(self, element):
        self.items.append(element)
        return self.items
    
    def remove_element(self, element):
        if element in self.items:
            self.items.remove(element)
            return True
        return False
    
    def display_list(self):
        return self.items

# Create instance
manager = ListManager()

# Add some elements
manager.add_element(10)
manager.add_element(20)
manager.add_element(30)

print("After adding elements:", manager.display_list())

# Remove an element
manager.remove_element(20)
print("After removing 20:", manager.display_list())

# Try to remove non-existent element
result = manager.remove_element(50)
print("Removing 50 (not in list):", result)
print("Final list:", manager.display_list())
After adding elements: [10, 20, 30]
After removing 20: [10, 30]
Removing 50 (not in list): False
Final list: [10, 30]

Enhanced Version with Error Handling

Here's an improved version with better error handling and user feedback ?

class AdvancedListManager:
    def __init__(self):
        self.items = []
    
    def add_element(self, element):
        self.items.append(element)
        print(f"Added '{element}' to list")
        return self.items
    
    def remove_element(self, element):
        try:
            self.items.remove(element)
            print(f"Removed '{element}' from list")
            return True
        except ValueError:
            print(f"Element '{element}' not found in list")
            return False
    
    def display_list(self):
        if self.items:
            print("Current list:", self.items)
        else:
            print("List is empty")
        return self.items
    
    def get_size(self):
        return len(self.items)

# Demonstrate the enhanced version
manager = AdvancedListManager()

# Test operations
manager.add_element("apple")
manager.add_element("banana")
manager.display_list()

manager.remove_element("apple")
manager.remove_element("orange")  # Not in list
manager.display_list()

print(f"List size: {manager.get_size()}")
Added 'apple' to list
Added 'banana' to list
Current list: ['apple', 'banana']
Removed 'apple' from list
Element 'orange' not found in list
Current list: ['banana']
List size: 1

Key Features

  • Encapsulation ? All list operations are contained within the class
  • Error Handling ? Proper handling of element removal when item doesn't exist
  • Clear Methods ? Descriptive method names like add_element(), remove_element()
  • Return Values ? Methods return appropriate values for further processing
  • User Feedback ? Clear messages about operations performed

Conclusion

Using classes to manage list operations provides better organization and reusability. The object-oriented approach encapsulates data and methods, making the code more maintainable and easier to extend with additional functionality.

Updated on: 2026-03-25T17:23:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements