Del statement and pop() method of list.
In : MSc IT Subject : Python ProgrammingUse del when:
You want to permanently remove elements without needing their values
You need to delete slices of a list
You want to delete entire variables from memory
You're doing memory cleanup operations
Use pop() when:
You need to access the removed element's value
You're implementing stack operations
You want to temporarily remove elements for processing
You're working with algorithms that require element retrieval during removal
Example :
# Example 1: Removing single elements
my_list1 = [1, 2, 3, 4, 5]
my_list2 = [1, 2, 3, 4, 5]
# Using del
del my_list1[2] # Removes element 3
print(my_list1) # [1, 2, 4, 5]
# Using pop()
removed = my_list2.pop(2) # Removes and returns element 3
print(removed) # 3
print(my_list2) # [1, 2, 4, 5]
# Example 2: Removing last element
my_list1 = [1, 2, 3, 4, 5]
my_list2 = [1, 2, 3, 4, 5]
# Using del
del my_list1[-1] # Removes last element
print(my_list1) # [1, 2, 3, 4]
# Using pop()
last = my_list2.pop() # Removes and returns last element
print(last) # 5
print(my_list2) # [1, 2, 3, 4]
# Example 3: Slice deletion (del only)
my_list = [1, 2, 3, 4, 5, 6]
del my_list[1:4] # Removes elements at indices 1, 2, 3
print(my_list) # [1, 5, 6]