Skip to main content

How to Remove an Item from a List in Python

Understand how to remove items from a list in Python. Familiarize yourself with methods like remove(), pop(), and del for list management.
Aug 1, 2024  · 7 min read

Lists appear frequently in Python programming, and for good reason. They help analysts organize, manage, and process data. For example, they dynamically grow or shrink in size when the data has a variable length. Lists can also be easily converted into other data types or structures, like tuples or arrays. They are even used as the building blocks in more advanced algorithms that require searching, sorting, and iterating through data.

Because Python is a versatile programming language, there are many ways to remove an item from a list in Python. In this tutorial, we will look at a few key methods, including built-in functions like remove() and pop(), list comprehensions, and the del keyword.

If you are an aspiring data analyst or data scientist, I highly recommend taking DataCamp’s Introduction to Python course to learn the basic skills of Python programming. The Python Cheat Sheet for Beginners will also be a helpful reference for mastering the syntax of different Python functions. 

3 Quick Methods to Remove List Items

You can use any of the following methods to remove an item from a list. In the first case, we can use the remove() function. 

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]
# Remove the element with the value 5 from the list
my_list.remove(5)

We can also use the pop() function. 

# Removes the last element from the list
last_element = my_list.pop()

We can also use the del keyword.

# Remove item at index 4
del my_list[4]

In each of the above cases, the new list will be [1, 2, 3, 4] after the element is removed.

Understanding Python Lists

Python lists are ordered collections of elements used to store any data type. Python lists are versatile and dynamic, allowing for different types of data manipulation. Due to their flexibility, lists in Python have the following use cases:

  • Data Storage: Lists are used to store collections of items, such as strings, numbers, and objects.
  • Data Manipulation: Lists can be used for various data manipulation and transformation tasks, including adding, removing, or modifying elements. 
  • Iteration: Lists are used in iteration to access and process every item sequentially.

It’s important to know, also, that Python lists are mutable, allowing modification even after creation. Therefore, one can add, remove, or modify the elements in the list as required.

Detailed Techniques for Removing Items from a List in Python

Python has different methods to remove items from a list. These techniques include the built-in method, keywords, and list comprehensions.

Using the remove() function

The remove() function is Python’s built-in method to remove an element from a list. The remove() function is as shown below.

list.remove(item)

Below is a basic example of using the remove() function. The function will remove the item with the value 3 from the list.

The remove() function will only remove the first occurrence of an item in a list if there are duplicates in the same list. In the following example, the remove() function removes only the first occurrence of 3 from the list.

# Define a list with some elements
my_list = [1, 2, 3, 4, 3]

# Use the remove() method to delete 3 from the list
# The remove() method removes the first occurrence of the specified value
my_list.remove(3)

# Print the list after removing 3
print(my_list)
[1, 2, 4, 3]

The remove() function will return a value error if an item is not in the list. Therefore, it is important to add an exception to handle such scenarios. The code below shows an example of catching the error for items not in the list.

# Initialize a list with color strings
colors = ["red", "green", "blue"]

# Try to remove the color "yellow" from the list
try:
    colors.remove("yellow")
# Catch the ValueError exception if "yellow" is not found in the list
except ValueError as e:
    print(e) 
list.remove(x): x not in list

Using the pop() function

The pop() function removes an item from a list by index. The syntax of the pop() function is shown below.

list.pop(index)

The example below shows how to use the pop() function to remove a specific item from a list by specifying the index. Note that you can store the removed element as a new list and return it.

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove and return the element at index 2 (third element) from the list
removed_item = my_list.pop(2)

# Print the updated list after removing the element
print(my_list)
print(removed_item)
[1, 2, 4, 5]
3

If you do not specify the index for the element to remove from the list, the pop() function will remove the last item in the list by default.

If you want to remove the first item from a list in Python, you will specify the index as 0 using the pop() function.

# Initialize a list with string elements from 'a' to 'd'
my_list = ["a", "b", "c", "d"]

# Remove and return the element at index 0 (the first element) from the list
removed_item = my_list.pop(0)

# Print the updated list after removing the element
print(my_list)
print(removed_item)
['b', 'c', 'd']
a

Similarly, if you want to remove the last item from a list, you will specify the last index as -1 using the pop() function.

# Initialize a list with string elements from 'a' to 'd'
my_list = ["a", "b", "c", "d"]

# Remove and return the element at index -1 (the last element) from the list
removed_item = my_list.pop(-1)

# Print the updated list after removing the last element
print(my_list)
print(removed_item)
['a', 'b', 'c']
d

If an item is out of range of the list, the pop() function will raise an IndexError. To handle the out-of-range indices, you should use the try-except block.

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Attempt to remove and return the element at index 10
# This will raise an IndexError because index 10 is out of range for the list
try:
    removed_item = my_list.pop(10)
# Catch the IndexError exception if the index is out of range
except IndexError as e:
    print(e) 
pop index out of range

Check out our latest tutorial on How to Use the Python pop() Method to learn more about removing elements from a list using this method.

Using the del keyword

The del keyword is useful in removing items or slices from a list in Python. The syntax for removing a single item from the list is shown below.

del list[index]

The example below shows how to remove a single item from a list using the del keyword.

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove item at index 2
del my_list[2]
print(my_list)
[1, 2, 4, 5]

Similarly, the del keyword provides the functionality to remove a slice of items from a list. The syntax for removing multiple  items is shown below where:

  • start indicates the start of the index of the slicing.

  • end indicates the end of the index of the slicing.

del list[start:end]

The example below shows the slicing technique of removing multiple items from a list using the del keyword.

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Delete the elements from index 1 to index 2 (elements 2 and 3) from the list
# This modifies the list to [1, 4, 5]
del my_list[1:3]
print(my_list) 
[1, 4, 5]

The del keyword also removes multiple items from a list using the step method. The syntax of the step method is shown below where:

  • start indicates the start of the index of the slicing.

  • end indicates the end of the index of the slicing.

  • step shows the intervals between slicing (1 by default).

del list[start:end:step]

The example below shows how to remove items from a list using the step method.

# Initialize a list with integers from 1 to 8
my_list = [1, 2, 3, 4, 5, 6, 7, 8]

# Delete elements from the list using slicing with a step of 2
del my_list[::2]
print(my_list)
[2, 4, 6, 8]

The advantages of using the del keyword in removing items from the list include the following:

  • Efficiency: The del keyword is memory efficient by allowing you to remove items in place, improving performance.

  • Versatility: Using the step method, the del keyword is useful in removing single items, slices or items, and multiple elements from a list.

However, the potential pitfalls of using the del keyword to remove items from a list include indexing errors, especially when an item is out of range. Therefore, using the try-except block to catch the IndexError is important.

# Initialize a list with integers 1, 2, and 3
my_list = [1, 2, 3]

# Attempt to delete the element at index 5
# This will raise an IndexError because index 5 is out of range for the list
try:
    del my_list[5]
# Catch the IndexError exception if the index is out of range
except IndexError as e:
    print(e) 
list assignment index out of range

When using the del keywords, you should be careful when specifying the slices to avoid unintended deletions, which can be difficult to debug.

Using list comprehensions

As a final section, we can consider list comprehensions. List comprehensions can be used to create new lists from an existing list, excluding some items. This technique is best used when removing an item from a list based on specific conditions. 

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Create a new list that includes all items from my_list except for the value 3
new_list = [item for item in my_list if item != 3]
print(new_list)
[1, 2, 4, 5]

Similarly, list comprehensions can be used to remove items based on condition. The example below shows how to use list comprehensions to remove even numbers from the original list.

# Initialize a list of integers from 1 to 10
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create a new list containing only the odd numbers from the original list
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers)
[1, 3, 5, 7, 9]

Using list comprehension in lists offers flexibility when handling complex scenarios, such as transforming data into a new format or creating lists from existing data structures. 

The example below shows how to use list comprehension to convert strings to uppercase and filter specific items.

# Initialize a list of fruit names
words = ["apple", "banana", "cherry", "avocado", "grape"]

# Create a new list containing the uppercase versions of words that start with the letter 'a'
a_words_upper = [word.upper() for word in words if word.startswith("a")]
print(a_words_upper)
['APPLE', 'AVOCADO']

List comprehensions can also be used to flatten and perform other operations in nested list comprehensions. In the example below, list comprehension was used to flatten the list and remove the odd numbers.

# Initialize a list containing sublists of integers
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Create a flat list of even numbers by iterating through each sublist
# and checking if each number is even
flat_even_numbers = [num for sublist in list_of_lists for num in sublist if num % 2 == 0]
print(flat_even_numbers) 
[2, 4, 6, 8]

Comparison table

Technique Use Case When Useful
remove() Remove specific items from a list When removing items from a list and handling duplicates
pop() Remove and return items from a specified list When you want to return the removed item from the list
del Remove items or slices of items from a list When removing multiple items or deleting elements in a list
List comprehension Create a new list based on the condition of the existing list For complex list operations, including filtering

If you want to understand more about list manipulation in data analysis, go through our Data Analyst with Python career track to grow your analytical skills.

Handling Multiple Occurrences and Conditions

When working with lists in Python, you may encounter scenarios when you need to remove multiple occurrences of items from a list. In such conditions, you will require a loop to iterate and remove the items.

Using loop and remove()

The following example shows how to use the loop and the remove() function to remove multiple item occurrences from a list.

# Initialize a list of integers
my_list = [1, 2, 3, 2, 4, 2, 5]

# Item to remove
item_to_remove = 2

# Loop to remove all occurrences
while item_to_remove in my_list:
    my_list.remove(item_to_remove)
print(my_list)
[1, 3, 4, 5]

Using loop and list comprehension

You can also use a loop in list comprehension to remove multiple occurrences of an item from a list.

# Initialize a list of integers
my_list = [1, 2, 3, 2, 4, 2, 5]

# Item to remove
item_to_remove = 2

# List comprehension to remove all occurrences
new_list = [item for item in my_list if item != item_to_remove]
print(new_list)
[1, 3, 4, 5]

Conclusion

Understanding when and how to apply the different list manipulation methods in your analysis task is essential. Also, ensure you know how to catch errors, handle edge cases, and use complex methods in list manipulation. I encourage you to experiment with the methods discussed above in your practice to find the most suitable approach for your different analyses.

If you want to learn more about Python for data analysis, try our Python Fundamentals skill track, which has a comprehensive data manipulation and transformation guide. Finally, DataCamp’s Python Programming skill track and Python Developer career track will offer you extensive skills to unlock a new chapter in your career.


Photo of Allan Ouko
Author
Allan Ouko
LinkedIn
I create articles that simplify data science and analytics, making them easy to understand and accessible.

Frequently Asked Questions

How do I remove an item from a list?

The built-in function remove() is useful in removing the first occurrence of an item in a list.

How do you handle duplicates in a list?

You can remove duplicates in a list using a loop in the remove() function or a loop in the list comprehension.

Can you remove items while iterating from a list?

You can use list comprehension to remove items from a list while iterating over it.

What is the difference between the remove() and pop() functions?

The remove() function removes an item from a list and returns the new list, while the pop() function removes an item from a list and returns the new list with the removed item.

Topics

Learn Python with DataCamp

course

Python Toolbox

4 hr
278.3K
Continue to build your modern Data Science skills by learning about iterators and list comprehensions.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Python: Remove Duplicates From A List (Five Solutions)

To remove duplicates from a Python list while preserving order, create a dictionary from the list and then extract its keys as a new list: list(dict.fromkeys(my_list)).
Stephen Gruppetta's photo

Stephen Gruppetta

9 min

tutorial

18 Most Common Python List Questions

Discover how to create a list in Python, select list elements, the difference between append() and extend(), why to use NumPy and much more.
Karlijn Willems's photo

Karlijn Willems

34 min

tutorial

How to Split Lists in Python: Basic Examples and Advanced Methods

Learn how to split Python lists with techniques like slicing, list comprehensions, and itertools. Discover when to use each method for optimal data handling.
Allan Ouko's photo

Allan Ouko

11 min

tutorial

Python Copy List: What You Should Know

Understand how to copy lists in Python. Learn how to use the copy() and list() functions. Discover the difference between shallow and deep copies.
Allan Ouko's photo

Allan Ouko

7 min

tutorial

How to Delete a File in Python

File management is a crucial aspect of code handling. Part of this skill set is knowing how to delete a file. In this tutorial, we cover multiple ways to delete a file in Python, along with best practices in doing so.
Amberle McKee's photo

Amberle McKee

5 min

tutorial

Python List Functions & Methods Tutorial and Examples

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Abid Ali Awan's photo

Abid Ali Awan

7 min

See MoreSee More