Remove elements from List using pop() method in Python

This tutorial will discuss multiple ways to remove elements from list using pop() method in Python.

Table Of Contents

Delete Element at given Index in List using pop() method

The list in Python provides a function called pop() that removes an element based on its index position. The pop() function takes the index position as an argument and removes the element at that given position. It also returns the removed element. If no argument is passed to the pop() function, it will remove the last element from the list. It’s important to note that if the provided index doesn’t exist in the list, the pop function will raise an IndexError.

To demonstrate, suppose we have a list of integers. To remove the second element from this list, we can call the pop() function and pass the index 1 (since indexing starts at 0). Doing so will remove the second element.

Let’s see the complete example,

# A List of Numbers
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]
print("Original List:", sampleList)

index = 1

# Remove element at index 1 in List i.e. 2nd element in list
deletedElement = sampleList.pop(index)

print('Deleted Element: ', deletedElement)
print(f"List after removing element at index {index}:", sampleList)

Output

Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51]
Deleted Element:  67
List after removing element at index 1: [45, 22, 45, 22, 89, 71, 22, 51]

Delete last element from List in Python

If you don’t pass any argument to the pop() function, it will, by default, remove the last element from the list.

Let’s see the complete example,

# A List of Numbers
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]
print("Original List:", sampleList)

# Remove Last element from List
deletedElement = sampleList.pop()

print('Deleted Element: ', deletedElement)
print(f"List after removing last element:", sampleList)

Output

Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51]
Deleted Element:  51
List after removing last element: [45, 67, 22, 45, 22, 89, 71, 22]

Summary

Today, we learned about remove elements from list using pop() method in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top