pop() method removes an element from a list and returns the removed value. By default, it removes the last element, but an index can be provided to remove an element from a specific position.
Example: In this example, pop() is used to remove the last element from a list.
a = [10, 20, 30, 40]
val = a.pop()
print(val)
print(a)
Output
40 [10, 20, 30]
Explanation: a.pop() removes and returns the last element of the list and removed value is stored in val.
Syntax
list.pop(index)
- Parameter: index (optional) - Position of the element to remove. Defaults to -1 (last element).
- Return Value: Returns the removed element and raises IndexError if the specified index is out of range.
Examples
Example 1: In this example, an index is provided to pop() so that an element can be removed from a particular position in the list.
a = ["red", "blue", "green", "yellow"]
val = a.pop(1)
print(val)
print(a)
Output
blue ['red', 'green', 'yellow']
Example 2: Here, pop() is used repeatedly to remove elements from the end of a list until it becomes empty.
a = [1, 2, 3]
while a:
print(a.pop())
Output
3 2 1
Explanation: a.pop() removes the last element during each iteration. Elements are removed in reverse order because pop() works from the end of the list by default.
Example 3: In this example, the value returned by pop() is used in another operation.
a = [5, 10, 15, 20]
num = a.pop()
print(num * 2)
print(a)
Output
40 [5, 10, 15]
Explanation: a.pop() removes and returns 20 and returned value is stored in num and used in the expression num * 2.