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
Show 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