Last Updated : 24 Oct, 2024
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():
Python
a = [10, 20, 30, 40]
# Remove the last element from list
a.pop()
print(a)
Explanation: a.pop() removes the last element, which is 40. The list a is now [10, 20, 30].
Syntax of pop() methodParameterslist_name.pop(index)
We can specify an index to remove an element from a particular position (index) in the list.
Python
a = ["Apple", "Orange", "Banana", "Kiwi"]
# Remove the 2nd index from list
val = a.pop(2)
print(val)
print(a)
Banana ['Apple', 'Orange', 'Kiwi']
Explanation:
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.
Python
a = [10, 20, 30, 40]
# Remove the last element from list
val = a.pop()
print(val)
print(a)
Explanation:
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:
Python
Output:
IndexError: pop index out of range
Explanation:
Related Articles:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4