The ‘pop()‘ method in Python can be used to remove (and also return) an item from a list based on a specific index. If no index is provided, the default behavior is to remove (and return) the last item from the list:
1. Remove and return the last item from a list (default behavior):
my_list = ["apple", "grape", "mango", "peach", "lemon"]
return_last_item = my_list.pop()
# Return the last item in the list
print(return_last_item)
# The list after removing the last item
print(my_list)
The result:
lemon
['apple', 'grape', 'mango', 'peach']
2. Remove and return an item based on a specific index (e.g., 2):
my_list = ["apple", "grape", "mango", "peach", "lemon"]
return_item_based_on_index = my_list.pop(2)
# Return an item based on a specific index
print(return_item_based_on_index)
# The list after removing the item
print(my_list)
The result:
mango
['apple', 'grape', 'peach', 'lemon']