The pop()
method in Python is a list method used to remove and return an element from a list based on the specified index. If no index is provided, it removes and returns the last element in the list. This method modifies the original list.
Parameter Values
Parameter | Description |
---|---|
index | An optional parameter specifying the index of the element to be removed from the list. If not provided, pop() removes and returns the last element of the list. |
Return Values
The pop()
method can return any data type that exists in the list, including None
.
How to Use pop()
in Python
The pop()
method removes and returns the element at the specified index in a list. If no index is specified, it removes and returns the last element in the list.
numbers = [1, 2, 3, 4, 5]
removed_number = numbers.pop(2)
print('Removed number:', removed_number)
print('Updated list:', numbers)
If the index provided is out of range, IndexError
is raised.
letters = ['a', 'b', 'c']
removed_letter = letters.pop(5)
print('Removed letter:', removed_letter)
print('Updated list:', letters)
Using pop()
without an index removes and returns the last element in the list.
fruits = ['apple', 'banana', 'orange', 'grape']
last_fruit = fruits.pop()
print('Last fruit removed:', last_fruit)
print('Updated list:', fruits)