Working with ArrayList - Python Programming Exercise

In this exercise, you will develop a Python program to demonstrate the use of an ArrayList-like structure. This exercise is perfect for practicing data structures, list manipulation, and dynamic resizing in Python. By implementing this program, you will gain hands-on experience in handling data structures, list manipulation, and dynamic resizing in Python. This exercise not only reinforces your understanding of data structures but also helps you develop efficient coding practices for managing user interactions.

 Category

Memory Management Techniques

 Exercise

Working With Arraylist

 Objective

Develop a Python program to demonstrate the use of an ArrayList-like structure. Use a list to simulate the functionality of an ArrayList, including operations to add, remove, and access elements. Ensure the program handles resizing the list dynamically as elements are added or removed.

 Example Python Exercise

 Copy Python Code
class ArrayList:
    """A class to simulate an ArrayList-like structure using a Python list."""
    
    def __init__(self):
        """Initialize the ArrayList with an empty list."""
        self.array = []  # The underlying list to store elements

    def add(self, element):
        """Adds an element to the end of the ArrayList."""
        self.array.append(element)
        print(f"Added: {element}")
    
    def remove(self, element):
        """Removes the first occurrence of the element from the ArrayList."""
        try:
            self.array.remove(element)
            print(f"Removed: {element}")
        except ValueError:
            print(f"Error: {element} not found in the list.")
    
    def get(self, index):
        """Returns the element at the specified index."""
        try:
            return self.array[index]
        except IndexError:
            print(f"Error: Index {index} out of range.")
            return None

    def size(self):
        """Returns the number of elements in the ArrayList."""
        return len(self.array)
    
    def is_empty(self):
        """Checks if the ArrayList is empty."""
        return len(self.array) == 0
    
    def display(self):
        """Displays all elements in the ArrayList."""
        if self.is_empty():
            print("The list is empty.")
        else:
            print("ArrayList contents:", self.array)

    def clear(self):
        """Removes all elements from the ArrayList."""
        self.array.clear()
        print("All elements removed from the list.")
    
    def resize(self):
        """Resizes the ArrayList (though resizing is handled automatically in Python)."""
        print(f"Resized the array to accommodate {self.size()} elements.")

def main():
    """Main function to interact with the ArrayList."""
    array_list = ArrayList()

    while True:
        print("\nOptions:")
        print("1. Add element")
        print("2. Remove element")
        print("3. Get element at index")
        print("4. Display list")
        print("5. Check list size")
        print("6. Check if the list is empty")
        print("7. Clear list")
        print("8. Exit")
        choice = input("Enter your choice: ")

        if choice == '1':
            element = input("Enter the element to add: ")
            array_list.add(element)
        
        elif choice == '2':
            element = input("Enter the element to remove: ")
            array_list.remove(element)
        
        elif choice == '3':
            index = int(input("Enter the index: "))
            element = array_list.get(index)
            if element is not None:
                print(f"Element at index {index}: {element}")
        
        elif choice == '4':
            array_list.display()
        
        elif choice == '5':
            print(f"List size: {array_list.size()}")
        
        elif choice == '6':
            if array_list.is_empty():
                print("The list is empty.")
            else:
                print("The list is not empty.")
        
        elif choice == '7':
            array_list.clear()
        
        elif choice == '8':
            print("Exiting the program.")
            break
        
        else:
            print("Invalid choice! Please try again.")

# Run the program
if __name__ == "__main__":
    main()

 Output

Options:
1. Add element
2. Remove element
3. Get element at index
4. Display list
5. Check list size
6. Check if the list is empty
7. Clear list
8. Exit
Enter your choice: 1
Enter the element to add: apple
Added: apple

Options:
1. Add element
2. Remove element
3. Get element at index
4. Display list
5. Check list size
6. Check if the list is empty
7. Clear list
8. Exit
Enter your choice: 4
ArrayList contents: ['apple']

Options:
1. Add element
2. Remove element
3. Get element at index
4. Display list
5. Check list size
6. Check if the list is empty
7. Clear list
8. Exit
Enter your choice: 2
Enter the element to remove: apple
Removed: apple

Options:
1. Add element
2. Remove element
3. Get element at index
4. Display list
5. Check list size
6. Check if the list is empty
7. Clear list
8. Exit
Enter your choice: 4
The list is empty.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  ArrayList Copying a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to duplicate the contents of a text file. This exercise is p...

  •  Calculating an Unlimited Sum

    In this exercise, you will develop a Python program to calculate an unlimited sum by continuously adding numbers provided by the user. This exercise is perfect...

  •  ArrayList - Reading a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to read and store the contents of a text file. This exercise...

  •  Hash Table - Implementing a Dictionary

    In this exercise, you will develop a Python program that implements a hash table using a dictionary. This exercise is perfect for practicing data structures, d...

  •  Parenthesis Matching

    In this exercise, you will develop a Python program that checks if parentheses in a given expression are properly balanced. This exercise is perfect for practi...

  •  Merging and Sorting Files

    In this exercise, you will develop a Python program that merges the contents of multiple text files into a single file and sorts the content alphabetically or numeric...