Python List pop()
The list pop()
method removes and returns the item at the specified index from a list. It modifies the original list.
Syntax
list.pop(index)
Parameters
index
(optional): The position of the element to be removed. If no index is provided, it removes and returns the last element of the list.
Return Value
Returns the removed item
Example 1: Removing an item at a specific index from the list
my_list = [5, 10, 15, 20]
# Remove item at index 1
removed_item = my_list.pop(1)
print(removed_item) # Output: 10
print(my_list) # Output: [5, 15, 20]
In Python, list indexes start from 0
. This means the first item is at the index 0, the second item is at the index 1
and so on. So to remove the second item from the list using the pop()
method, you need to pass 1
as the index.
Example 2: Removing the last item from the list
my_list = ["apple", "banana", "mango", "orange"]
# Remove the last item
removed_item = my_list.pop()
print(removed_item) # Output: orange
print(my_list) # Output: ['apple', 'banana', 'mango']
If no index is passed to the pop()
method, it removes and returns the last item in the list by default.
Example 3: Removing the first item from the list
my_list = ["apple", "banana", "mango", "orange"]
# Remove the first item
removed_item = my_list.pop(0)
print(removed_item) # Output: apple
print(my_list) # Output: ['banana', 'mango', 'orange']
Error Handling
Error handling is necessary when using pop()
method in Python. The most common issue is an IndexError
, which occurs if you try to remove an item from the empty list or use an index that is out of range.
Example 1: Error handling for an empty list
my_list = []
try:
removed_item = my_list.pop()
except IndexError:
print("Cannot pop from empty list!")
# Output: Cannot pop from empty list!
Example 2: Error handling with invalid index
my_list = ["apple", "banana", "mango", "kiwi"]
try:
removed_item = my_list.pop(10)
except IndexError:
print("Error: Index is out of range.")
# Output: Error: Index is out of range.
If you want to remove an element by its value, you can use the remove()
method.