How to Use the Python List pop() Method
![](https://plantpot.works/wp-content/uploads/2021/09/7298.png)
Contents
In this article, you will learn how to use the Python list pop() method.
Python List pop() Method
The pop() method is a built-in function in Python lists that removes and returns the last element of a list. Here’s how to use the pop() method:
Syntax
list.pop([index])
Parameters
index
: Specifies which element to remove and return. If the index is not specified, the last element is removed and returned.
Example
fruits = ['apple', 'banana', 'cherry']
popped_fruit = fruits.pop()
print(popped_fruit) # Output: 'cherry'
print(fruits) # Output: ['apple', 'banana']
In this example, the pop() method removes and returns the last element of the fruits list, which is ‘cherry’. The popped element is then assigned to the popped_fruit variable. Finally, the contents of the fruits list are printed, which shows that ‘cherry’ has been removed.
If you want to remove and return a specific element in the list, you can pass its index as an argument to the pop() method. For example:
fruits = ['apple', 'banana', 'cherry']
popped_fruit = fruits.pop(1)
print(popped_fruit) # Output: 'banana'
print(fruits) # Output: ['apple', 'cherry']
In this example, the pop() method removes and returns the element at index 1, which is ‘banana’. The popped element is then assigned to the popped_fruit variable. Finally, the contents of the fruits list are printed, which shows that ‘banana’ has been removed and the remaining elements have been shifted left.