Deleting Elements from a List
1. del Statement
Used to delete elements by index or to delete slices. It does not return the deleted value.
python my_list = ['A', 'B', 'C', 'D', 'E']
del my_list[1] # Deletes 'B' print(my_list) # ['A', 'C', 'D', 'E']
del my_list[2:] # Deletes slice from index 2 onwards ('D', 'E') print(my_list) # ['A', 'C']
2. pop() Method
Removes an element at a specific index and returns the value of the removed element. If no index is specified, it removes and returns the last item.
python stack = ['Data1', 'Data2', 'Data3']
last_item = stack.pop() # Removes 'Data3' print(f"Removed: {last_item}") # Removed: Data3 print(stack) # ['Data1', 'Data2']
first_item = stack.pop(0) # Removes item at index 0 ('Data1') print(stack) # ['Data2']
3. remove() Method
Removes the first occurrence of a specified value.
python colors = ['red', 'blue', 'green', 'blue'] colors.remove('blue') print(colors) # ['red', 'green', 'blue'] (Only the first 'blue' was removed)