Python List pop() Method (original) (raw)
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].
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.
Python `
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.
Python `
a = [10, 20, 30, 40]
Remove the last element from list
val = a.pop()
print(val) print(a)
`
**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:
Python `
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: