Python 3 – List pop() Method
In Python, a list is a collection of items that can be changed, added or removed at any time. The list pop()
method is one such method that helps in removing a specific item from the list. In this article, we will explore this method in detail.
The pop()
method is used to remove an item from the list at a specific index position. Let’s take a look at the syntax below:
list.pop(index)
Here, list
is the name of the list from which you want to remove an item, and index
is the position/index of the item to be removed. If the index is not specified, the method will remove and return the last item in the list.
Let’s look at some examples to better understand the pop()
method.
Example 1: Removing an item from a specific index
# Define a list
fruits = ['apple', 'banana', 'cherry', 'date']
# Remove the item at index 2
fruits.pop(2)
print(fruits)
Output:
['apple', 'banana', 'date']
In the example above, we defined a list called fruits
. We then used the pop()
method to remove the item at index 2, which was 'cherry'
. Finally, we printed the updated list.
Example 2: Removing the last item from the list
# Define a list
fruits = ['apple', 'banana', 'cherry', 'date']
# Remove the last item
fruits.pop()
print(fruits)
Output:
['apple', 'banana', 'cherry']
In the example above, we again defined the list fruits
. However, this time we did not specify an index to remove. Therefore, the pop()
method removed and returned the last item in the list, which was 'date'
.
Example 3: Using the pop()
method to access and remove an item
# Define a list
fruits = ['apple', 'banana', 'cherry', 'date']
# Access and remove the item at index 1
removed_item = fruits.pop(1)
print('Removed item:', removed_item)
print('Updated list:', fruits)
Output:
Removed item: banana
Updated list: ['apple', 'cherry', 'date']
In the example above, we defined the list fruits
. We then used the pop()
method to remove and return the item at index 1, which was 'banana'
. We stored this returned item in a variable called removed_item
. Finally, we printed the removed item and the updated list.
Example 4: Using the pop()
method with a negative index
# Define a list
fruits = ['apple', 'banana', 'cherry', 'date']
# Access and remove the item at index -1
removed_item = fruits.pop(-1)
print('Removed item:', removed_item)
print('Updated list:', fruits)
Output:
Removed item: date
Updated list: ['apple', 'banana', 'cherry']
Here, we defined the list fruits
and used the pop()
method to remove and return the item at index -1, which is the last item in the list. This is equivalent to removing the last item like we did in Example 2. Finally, we printed the removed item and the updated list.
Conclusion
In conclusion, the pop()
method is a useful feature of Python lists that allows you to remove an item at a specific index position or the last item in the list. By understanding how to use this method, you can more easily manipulate and customize your Python lists in your code.