Table of contents
1.
Introduction
2.
remove(): Deleting Specific Elements
2.1.
How to Use remove()
2.2.
Python
3.
del: Removing Elements by Index
3.1.
How to Use del
3.2.
Python
4.
pop(): Removing & Retrieving Elements
4.1.
How to Use pop()
4.2.
Python
5.
Remove Element from the List using List Comprehension
5.1.
Python
6.
Remove Element from the List Using discard()
6.1.
Python
7.
Remove Element From the List Using filter()
7.1.
Python
8.
Remove Element from the List Using Slicing
8.1.
Python
9.
Remove Element from the List Using Itertools
9.1.
Python
10.
Frequently Asked Questions
10.1.
What happens if I use pop() on an empty list?
10.2.
Can remove() delete multiple instances of an element at once?
10.3.
Is there a performance difference between del, remove(), and pop()?
11.
Conclusion
Last Updated: Sep 27, 2024
Easy

Python Delete From List

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python, deleting elements from a list is a very basic but important operation that allows you to remove one or more items from a list. You can delete elements based on their index or value using various methods such as `remove()`, `pop()`, or `del` statements. Deleting elements from a list modifies the list in place, updating its size and shifting the remaining elements accordingly. In this article, we'll learn about different ways to delete items from a list in Python, including using the remove() method, the del statement, & the pop() method. 

Python Delete From List

remove(): Deleting Specific Elements

When you need to delete a specific element from a list in Python, the remove() method is incredibly useful. This method searches for the first occurrence of the given element & removes it from the list. It's important to note that if the element isn't found, Python will raise a ValueError, so you might want to check if the element exists in the list before attempting to remove it.

How to Use remove()

Here’s a simple example to demonstrate how remove() works:

  • Python

Python

# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Remove 'banana' from the list
fruits.remove('banana')

# Print the updated list
print(fruits)
You can also try this code with Online Python Compiler
Run Code

Output

['apple', 'cherry', 'date'].


In this example, 'banana' is removed from the fruits list, & the updated list will display ['apple', 'cherry', 'date'].

The remove() method is ideal for situations where you know the exact element you wish to delete. However, it's not suitable for removing elements by index or when you need to delete multiple identical elements, as it only removes the first match it finds.

del: Removing Elements by Index

The del statement in Python is a powerful tool for directly modifying lists by removing elements based on their index, the position of the element in the list. Unlike the remove() method, which targets elements by value, del lets you delete elements at specific positions, and it can also handle slicing to remove ranges of elements.

How to Use del

Here’s an example that shows how to delete a single element and a slice of elements from a list:

  • Python

Python

# Define a list of integers
numbers = [10, 20, 30, 40, 50]

# Delete the third element
del numbers[2]

# Now delete a range of elements, from index 1 to 2
del numbers[1:3]

# Print the updated list
print(numbers)
You can also try this code with Online Python Compiler
Run Code

Output

[10, 50]


In this code:

  • del numbers[2] removes the element at index 2, which is 30.
     
  • del numbers[1:3] removes the elements starting from index 1 up to, but not including, index 3. After the first deletion, this would result in removing 20 and what was originally the 40.
     
  • The list initially was [10, 20, 30, 40, 50] and ends up as [10, 50] after these operations. This example illustrates how del can be used for precise control over which elements are removed, based on their position.


Note -: Using del is particularly useful when you need to manage lists dynamically, adjusting their contents as your program runs. However, you must be cautious with indices to avoid errors, such as IndexError, which occurs if you try to delete an element that doesn't exist at a specified index.

pop(): Removing & Retrieving Elements

The pop() method combines functionality of both deletion and retrieval, allowing you to remove an element from a list and return it at the same time. This method is particularly useful when you need to work with the element you are removing, such as when processing and removing items from a stack or queue.

How to Use pop()

Here’s how you can use the pop() method:

  • Python

Python

# Define a list of colors
colors = ['red', 'green', 'blue', 'yellow']

# Pop the last element
popped_color = colors.pop()

# Pop a specific element by index
popped_index_color = colors.pop(1)

# Print the popped colors
print("Popped color:", popped_color)
print("Popped color from index:", popped_index_color)

# Print the remaining list
print("Remaining colors:", colors)
You can also try this code with Online Python Compiler
Run Code

Output

Popped color: yellow
Popped color from index: green
Remaining colors: ['red', 'blue']


In this example:

popped_color holds 'yellow', which is the last item in the list removed by pop().

popped_index_color holds 'green', which is removed from the index position 1.

After these operations, the colors list initially [red, green, blue, yellow] ends up as [red, blue]. The pop() method is very flexible, allowing you to choose either the last item or any item by specifying its index. If no index is given, pop() removes the last item by default. Be cautious, though; if you try to pop from an empty list, or an invalid index, Python will raise an IndexError.

Note -: The pop() method is ideal for situations where elements need to be processed and then removed, ensuring that no data is lost in the process.

Remove Element from the List using List Comprehension

List comprehension is a concise way to create new lists based on existing lists or other iterable objects. It can also be used to remove elements from a list based on a specified condition. Let's see you can use list comprehension to remove elements from a list:

new_list = [item for item in original_list if condition]

 

Explanation:

  • `new_list`: The new list that will be created after removing elements from the original list.
  • `item`: The variable that represents each element in the original list.
  • `original_list`: The list from which elements will be removed.
  • `condition`: The condition that determines whether an element should be included in the new list or not. Elements that satisfy the condition will be included, while elements that don't satisfy the condition will be removed.

 

For example : 

  • Python

Python

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Remove even numbers from the list using list comprehension
odd_numbers = [num for num in numbers if num % 2 != 0]

print("Original list:", numbers)
print("List after removing even numbers:", odd_numbers)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after removing even numbers: [1, 3, 5, 7, 9]

In this example, the original list `numbers` contains integers from 1 to 10. Using list comprehension, a new list `odd_numbers` is created, which includes only the odd numbers from the original list. The condition `num % 2 != 0` checks if each number is not divisible by 2 (i.e., it is an odd number). Only the elements that satisfy this condition are included in the new list.

It's important to note that list comprehension creates a new list without modifying the original list. If you want to modify the original list directly, you can use other methods like `remove()` or `del` statements.

Remove Element from the List Using discard()

In Python, the `discard()` method is a built-in function of the `set` data type. It is used to remove a specified element from a set. However, if you have a list and want to remove elements from it using `discard()`, you need to convert the list to a set first. Here's how you can use `discard()` to remove elements from a list:

# Convert the list to a set
set_from_list = set(original_list)
# Remove the desired element using discard()
set_from_list.discard(element)
# Convert the set back to a list (if needed)
new_list = list(set_from_list)

 

Explanation:
1. Convert the list to a set using the `set()` function. This step is necessary because `discard()` is a method of the `set` data type.
2. Use the `discard()` method on the set, passing the element you want to remove as an argument. If the element exists in the set, it will be removed. If the element doesn't exist, no error will be raised, and the set will remain unchanged.
3. If you need the result as a list, convert the set back to a list using the `list()` function.

 

For example : 

  • Python

Python

# Original list
fruits = ['apple', 'banana', 'orange', 'grape', 'banana']

# Convert the list to a set
fruit_set = set(fruits)

# Remove 'banana' using discard()
fruit_set.discard('banana')

# Convert the set back to a list
new_fruits = list(fruit_set)

print("Original list:", fruits)
print("List after removing 'banana':", new_fruits)
You can also try this code with Online Python Compiler
Run Code


Output:

Original list: ['apple', 'banana', 'orange', 'grape', 'banana']
List after removing 'banana': ['apple', 'orange', 'grape']

In this example, the original list `fruits` contains duplicate elements. By converting the list to a set using `set()`, the duplicate elements are automatically removed. Then, the `discard()` method is used to remove the element `'banana'` from the set. Finally, the set is converted back to a list using `list()` to obtain the new list `new_fruits` with the element `'banana'` removed.

Note that `discard()` removes the specified element from the set only if it exists. If the element doesn't exist, no error is raised, making it a safe method to use when you're not sure if the element is present in the set.

Also, keep in mind that converting a list to a set and then back to a list may change the order of the elements and remove any duplicates that were present in the original list.

Remove Element From the List Using filter()

In Python, the `filter()` function is a built-in function that allows you to remove elements from a list based on a specified condition. It takes two arguments: a function that defines the filtering condition and the list from which elements need to be removed. The `filter()` function returns an iterator containing the elements that satisfy the condition. Here's how you can use `filter()` to remove elements from a list:

new_list = list(filter(lambda item: condition, original_list))

 

Explanation:

  • `new_list`: The new list that will be created after removing elements from the original list.
  • `filter()`: The built-in function that filters the elements based on a condition.
  • `lambda item: condition`: An anonymous function (lambda function) that defines the filtering condition. It takes an item from the list as input and returns `True` if the item should be included in the new list, or `False` if the item should be removed.
  • `original_list`: The list from which elements will be removed.
  • `list()`: The `filter()` function returns an iterator, so we convert it to a list using the `list()` function to get the final result.

 

For example : 

  • Python

Python

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Remove even numbers from the list using filter()
odd_numbers = list(filter(lambda num: num % 2 != 0, numbers))

print("Original list:", numbers)
print("List after removing even numbers:", odd_numbers)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after removing even numbers: [1, 3, 5, 7, 9]

 

In this example, the original list `numbers` contains integers from 1 to 10. The `filter()` function is used with a lambda function `lambda num: num % 2 != 0` as the filtering condition. This lambda function checks if each number is not divisible by 2 (i.e., it is an odd number). The `filter()` function returns an iterator containing only the odd numbers from the original list. Finally, the `list()` function is used to convert the iterator to a new list `odd_numbers`.

The `filter()` function is useful when you want to remove elements from a list based on a specific condition. The condition can be any expression that evaluates to `True` or `False` for each element in the list.

Note that `filter()` creates a new list containing the filtered elements, leaving the original list unmodified. If you want to modify the original list directly, you can use list comprehension or other methods like `remove()` or `del` statement.

Remove Element from the List Using Slicing

In Python, you can use slicing to remove elements from a list by creating a new list that excludes the desired elements. Slicing allows you to specify a range of indices to include in the new list, effectively removing the elements outside that range. Here's how you can use slicing to remove elements from a list:

new_list = original_list[:start] + original_list[end:]

Explanation:

  • `new_list`: The new list that will be created after removing elements from the original list.
  • `original_list`: The list from which elements will be removed.
  • `start`: The starting index of the range of elements to be removed (inclusive).
  • `end`: The ending index of the range of elements to be removed (exclusive).

The slicing operation `original_list[:start] + original_list[end:]` creates a new list by concatenating two slices of the original list:

  • `original_list[:start]`: This slice includes all elements from the beginning of the list up to, but not including, the element at index `start`.
  • `original_list[end:]`: This slice includes all elements from the element at index `end` to the end of the list.

By concatenating these two slices, you effectively remove the elements between indices `start` and `end` (excluding `end`) from the original list.

 

For example : 

  • Python

Python

# Original list
fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']

# Remove elements from index 1 to 3 (excluding 3) using slicing
new_fruits = fruits[:1] + fruits[3:]

print("Original list:", fruits)
print("List after removing elements:", new_fruits)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Original list: ['apple', 'banana', 'orange', 'grape', 'kiwi']
List after removing elements: ['apple', 'grape', 'kiwi']

 

In this example, the original list `fruits` contains strings representing different fruits. The slicing operation `fruits[:1] + fruits[3:]` creates a new list `new_fruits` by concatenating two slices of the original list:

  1. `fruits[:1]`: This slice includes all elements from the beginning of the list up to, but not including, the element at index 1 (i.e., `'apple'`).
  2. `fruits[3:]`: This slice includes all elements from the element at index 3 (i.e., `'grape'`) to the end of the list.

By concatenating these two slices, the elements at indices 1 and 2 (`'banana'` and `'orange'`) are effectively removed from the new list.

Slicing provides a concise way to remove elements from a list by creating a new list with the desired elements. It is particularly useful when you want to remove a contiguous range of elements based on their indices.

Note that slicing creates a new list and does not modify the original list. If you want to modify the original list directly, you can use the `del` statement with slicing, like `del original_list[start:end]`.

Remove Element from the List Using Itertools

In Python, the `itertools` module provides a set of functions for working with iterators and creating efficient looping constructs. One of the functions in `itertools` that can be used to remove elements from a list is `itertools.filterfalse()`. This function is equivalent to the built-in `filter()` function, but it returns the elements for which the specified condition is `False`. Let's see how you can use `itertools.filterfalse()` to remove elements from a list:

from itertools import filterfalse
new_list = list(filterfalse(lambda item: condition, original_list))

 

Explanation:

  1. `from itertools import filterfalse`: This line imports the `filterfalse()` function from the `itertools` module.
  2. `new_list`: The new list that will be created after removing elements from the original list.
  3. `filterfalse()`: The function from the `itertools` module that filters the elements based on a condition.
  4. `lambda item: condition`: An anonymous function (lambda function) that defines the filtering condition. It takes an item from the list as input and returns `True` if the item should be removed from the new list, or `False` if the item should be included.
  5. `original_list`: The list from which elements will be removed.
  6. `list()`: The `filterfalse()` function returns an iterator, so we convert it to a list using the `list()` function to get the final result.

 

For example : 

  • Python

Python

from itertools import filterfalse

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Remove odd numbers from the list using itertools.filterfalse()
even_numbers = list(filterfalse(lambda num: num % 2 != 0, numbers))

print("Original list:", numbers)
print("List after removing odd numbers:", even_numbers)
You can also try this code with Online Python Compiler
Run Code


Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after removing odd numbers: [2, 4, 6, 8, 10]

In this example, the original list `numbers` contains integers from 1 to 10. The `filterfalse()` function is used with a lambda function `lambda num: num % 2 != 0` as the filtering condition. This lambda function checks if each number is not divisible by 2 (i.e., it is an odd number). The `filterfalse()` function returns an iterator containing only the even numbers from the original list, effectively removing the odd numbers. Finally, the `list()` function is used to convert the iterator to a new list `even_numbers`.

`itertools.filterfalse()` is similar to using the built-in `filter()` function, but it removes the elements for which the condition is `False` instead of keeping them.

Important point to remember is that `filterfalse()` creates a new list containing the filtered elements, leaving the original list unmodified. If you want to modify the original list directly, you can use list comprehension or other methods like `remove()` or `del` statement.

Frequently Asked Questions

What happens if I use pop() on an empty list?

If you attempt to use pop() on an empty list, Python will raise an IndexError indicating that you are trying to pop from an empty list. Always ensure the list has elements before using pop().

Can remove() delete multiple instances of an element at once?

No, the remove() method only deletes the first occurrence of the specified element. If you need to remove all instances, you'll need to use a loop or a list comprehension to apply remove() repeatedly.

Is there a performance difference between del, remove(), and pop()?

Yes, there can be. del is generally faster because it directly deletes an element by index. remove() searches through the list to find the element before removing it, which can take longer especially for large lists. pop() is efficient for removing elements from the end of the list but can be slower when popping by index due to the need to shift elements.

Conclusion

In this article, we have learned about different methods to delete elements from a list in Python. We explored remove(), which is useful for deleting an element by value, del for removing elements by their index or slicing out sections of a list, and pop(), which not only deletes an element but also returns it. Understanding these methods allows for more effective and efficient data manipulation in Python, enhancing both the functionality and performance of your code. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass