Junior — Middle
What is the difference between the pop and delete methods when working with lists in Python?
sobes.tech AI
Answer from AI
The pop method in Python removes an element from a list by index and returns it. If no index is specified, it removes the last element. This is convenient when you need to get the removed element.
Example:
lst = [10, 20, 30]
item = lst.pop(1) # removes the element at index 1 (20) and returns it
print(item) # 20
print(lst) # [10, 30]
The del operator removes an element or slice from a list by index but does not return it. It is used for deletion without needing to get the value.
Example:
lst = [10, 20, 30]
del lst[1] # removes the element at index 1
print(lst) # [10, 30]
Summary:
popremoves and returns the elementdelsimply removes the element without returning
pop is useful when you need the removed element, del when you just want to delete.