Python’s pop() Method: Simplifying List Manipulation and Data Removal

Python’s pop() Method: Simplifying List Manipulation and Data Removal

6 mins read147 Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Apr 30, 2024 09:35 IST

The pop() method is a built-in function in Python that allows you to remove and return an item from a list. It removes items from a list’s end or a specific index. Additionally, error handling is important when using the pop() method to prevent the program from crashing. Advanced examples of the pop() method include removing duplicates from a list and reversing the order of elements in a list.

2023_02_MicrosoftTeams-image-193.jpg

Table of Content

 

Introduction to Python pop() method

What is the pop() method in Python?

In Python, the pop() method is a built-in method that allows you to remove an item from a list. It removes the item at a specified index by default, but you can also use it to remove the last item in the list. The pop() method not only removes the item from the list but also returns the removed item. This can be useful when you need to manipulate the data in a list or when you want to store the removed item for future use. The pop() method is a versatile tool for manipulating lists in Python, and it can help streamline your code by allowing you to remove data from lists easily.

Must Check: Top 10 Python Built-in Functions

What is Programming What is Python
What is Data Science What is Machine Learning

Syntax

The syntax of the pop() method in Python is as follows:


 
list_name.pop([index])
Copy code

Here, “list_name” refers to the name of the list that you want to remove an item from. The “index” parameter is optional, specifying the item’s position to be removed. If you omit the “index” parameter, pop() will remove and return the last item in the list.

If you provide an index value, pop() will remove the item at that index and return it. After removing the item, the list will be updated so that the remaining items shift to fill the gap left by the removed item. If the index value provided is out of range (i.e., greater than or equal to the length of the list), the pop() method will raise an IndexError.

Note that the pop() method modifies the original list; it does not create a new list. If you want to remove an item without modifying the original list, you can create a copy of the list and then use the pop() method on the copy.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Examples of pop() method in Python

Example-1: Removing an Item from the End of a List using pop()


 
fruits = ['apple', 'banana', 'orange', 'mango']
last_fruit = fruits.pop()
print(last_fruit) # Output: mango
print(fruits) # Output: ['apple', 'banana', 'orange']
Copy code

Output

In this example, we first define a ” fruits ” list containing four elements. We then call the pop() method on the “fruits” list without providing any argument. Since no index is specified, the pop() method removes and returns the list’s last element, “mango”. We store this value in a variable called “last_fruit” and then print it to the console.

After removing “mango” from the “fruits” list, the list is updated to contain only the remaining three fruits: “apple”, “banana”, and “orange”. We then print the updated “fruits” list to confirm that “mango” has been removed.

Using pop() to remove the last item from a list can be especially useful when processing a list in reverse order. By repeatedly calling pop() on the list, you can efficiently iterate over its elements in reverse order.

Example-2: Removing an Item from a Specific Index using pop()


 
fruits = ['apple', 'banana', 'orange', 'mango']
removed_fruit = fruits.pop(1)
print(removed_fruit) # Output: banana
print(fruits) # Output: ['apple', 'orange', 'mango']
Copy code

Output

In this example, we define a ” fruits ” list containing four elements. We then call the pop() method on the “fruits” list and pass in an argument of 1, which corresponds to the index of the second element (“banana”) in the list. The pop() method removes and returns this element, which we store in a variable called “removed_fruit”. We then print “removed_fruit” and the updated “fruits” list to confirm that “banana” has been removed from the list.

Note that after removing “banana” from the list, the remaining elements shift to fill the gap left by the removed element. This means that the element at index 2 (“orange”) becomes the new element at index 1, and the element at index 3 (“mango”) becomes the new element at index 2.

If you try to remove an element from an index that is out of range, the pop() method will raise an IndexError. So be sure to double-check that the index you provide is valid for the length of the list.

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Example -3: Removing Duplicate Elements from a List


 
fruits = ['apple', 'banana', 'orange', 'banana', 'mango', 'orange']
unique_fruits = []
while fruits:
fruit = fruits.pop()
if fruit not in unique_fruits:
unique_fruits.append(fruit)
print(unique_fruits) # Output: ['orange', 'mango', 'banana', 'apple']
Copy code

Output

In this example, we define a list called “fruits” that contains six elements, including two duplicates: ‘banana’ and ‘orange’. We want to remove the duplicates and create a new list containing only the unique fruits.

To achieve this, we use a while loop to iterate over the “fruits” list. Inside the loop, we call the pop() method to remove the last element from the list and store it in a variable called “fruit”. We then check if “fruit” is already in the “unique_fruits” list using the “not in” operator. If not, we append it to the “unique_fruits” list.

After all the elements have been removed from the “fruits” list, we print the “unique_fruits” list, which contains only the unique fruits in the original list.

Also Read: All about Python Lists Method

Example-4: Reversing a List using pop()


 
fruits = ['apple', 'banana', 'orange', 'mango']
reversed_fruits = []
while fruits:
reversed_fruits.append(fruits.pop())
print(reversed_fruits) # Output: ['mango', 'orange', 'banana', 'apple']
Copy code

Output

In this example, we define a ” fruits ” list containing four elements. We want to reverse the order of the elements and create a new list containing the reversed elements.

To do this, we use a while loop to iterate over the “fruits” list. We call the pop() method inside the loop to remove the last element from the list and append it to a new list called “reversed_fruits”.

After all the elements have been removed from the “fruits” list and appended to the “reversed_fruits” list, we print the “reversed_fruits” list to the console, which contains the elements in reverse order compared to the original “fruits” list.

Also Read: Python Lists Practice Program for Beginners

Error Handling in pop() method

When using the pop() method in Python, it’s important to handle errors that may occur. The most common error you may encounter when using the pop() method is an IndexError, which occurs when you try to remove an item from an index that is out of range.

Here’s an example of how to handle an IndexError when using the pop() method:


 
fruits = ['apple', 'banana', 'orange']
try:
removed_fruit = fruits.pop(3)
print(removed_fruit)
except IndexError:
print("Error: Index out of range")
Copy code

Output

In this example, we define a list called “fruits” that contains three elements. We then call the pop() method on the “fruits” list and pass in an argument of 3, which is out of range since the list only has three elements. This would normally raise an IndexError.

To handle this error, we wrap the pop() method call in a try-except block. If an IndexError is raised, the except block will execute and print an error message (“Error: Index out of range”) to the console.

Using error handling with the pop() method, you can prevent your program from crashing or producing unexpected results when it encounters an error.

Also Read: Python try-except

Conclusion

In conclusion, the pop() method in Python is a useful built-in function that allows you to remove and return an item from a list. It removes items from a list’s end or a specific index. Error handling is important when using the pop() method to prevent program crashes. By utilizing the pop() method, you can easily modify lists to suit your needs. With the advanced examples provided, it’s clear that the pop() method is a versatile tool that can be used in various ways, making it an important part of any Python developer’s toolkit.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio