Python List pop() Method
The pop() method is used to remove an element from a list at a specified index and return that element. If no index is provided, it will remove and return the last element by default. This method is particularly useful when we need to manipulate a list dynamically, as it directly modifies the original list.
Let’s take an example to remove an element from the list using pop():
a = [10, 20, 30, 40]
# Remove the last element from list
a.pop()
print(a)
Output
[10, 20, 30]
Explanation: a.pop() removes the last element, which is 40. The list a is now [10, 20, 30].
Table of Content
Syntax of pop() method
list_name.pop(index)
Parameters
- index (optional): index of an item to remove. Defaults to -1 (last item) if argument is not provided.
Return Value
- Returns the removed item from the specified index
- Raises IndexError if the index is out of range.
Using pop() with an index
We can specify an index to remove an element from a particular position (index) in the list.
a = ["Apple", "Orange", "Banana", "Kiwi"]
# Remove the 2nd index from list
val = a.pop(2)
print(val)
print(a)
Output
Banana ['Apple', 'Orange', 'Kiwi']
Explanation:
- a.pop(2) removes the element at index 2, which is “Banana“.
- val stores the value Banana.
- The list a is now [“Apple”, “Orange”, “Kiwi”].
Using pop() without an index
If we don’t pass any argument to the pop() method, it removes the last item from the list because the default value of the index is -1.
a = [10, 20, 30, 40]
# Remove the last element from list
val = a.pop()
print(val)
print(a)
Output
40 [10, 20, 30]
Explanation:
- a.pop() removes the last element, which is 40.
- val stores the value 40.
- After using pop(), the list a is updated to [10, 20, 30].
Handling IndexErrors
The pop() method will raise an IndexError if we try to pop an element from an index that does not exist. Let’s see an example:
a = [1, 2, 3]
a.pop(5)
Output:
IndexError: pop index out of range
Explanation:
- The list a has only three elements with valid indices 0, 1, and 2.
- Trying to pop from index 5 will raise an IndexError.
Related Articles:
- Python – Remove first element of list
- Python – Remove rear element from list
- Python | Remove given element from the list