Understanding Python list.pop() Method with Examples
This article explains Python's list.pop() method, covering its syntax, optional index parameter, error handling, return value, and provides multiple code examples demonstrating removal by specific, default, and negative indices, along with outputs and a brief note on alternative deletion methods.
Python's list pop() is a built‑in function that removes an item at a specified index from a list and returns the removed item; if no index is provided, it removes and returns the last element.
Basic syntax: list.pop(index) where index is optional. If omitted, -1 is used. If the index is out of range, an IndexError is raised.
The method returns the element that was removed.
Example 1 demonstrates removing the element at index 4 (the fifth item) from a list of laptop brands and printing the removed item and the updated list.
<code>laptops = ["Dell","Lenovo","HP","Apple","Acer","Asus"]
item_removed = laptops.pop(4)
print("The item removed is ", item_removed)
print("The updated list is ", laptops)</code>Output:
<code>The item removed is Acer
The updated list is ['Dell', 'Lenovo', 'HP', 'Apple', 'Asus']</code>Example 2 shows using pop() without an index (defaulting to the last element) and with negative indices to remove elements from the end of the list.
<code>laptops = ["Dell","Lenovo","HP","Apple","Acer","Asus"]
item_removed = laptops.pop()
print("The item removed is ", item_removed)
print("The updated list is ", laptops)
item_removed = laptops.pop(-1)
print("The item removed is ", item_removed)
print("The updated list is ", laptops)
item_removed = laptops.pop(-3)
print("The item removed is ", item_removed)
print("The updated list is ", laptops)</code>Corresponding output shows the removed items and the lists after each operation.
In addition to pop(), Python also provides remove() and the del statement for deleting items or slices from a list.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.