Remove list in list Python

In this tutorial, youll learn how to use Python to remove an item from a list. Youll learn how to do this using the pop, remove, del, and clear methods, as well as how to remove just one instance of an item or all instances. Youll also learn how to remove multiple Python list items conditionally.

Python lists are mutable data types, meaning that they can be changed. They are also indexed, meaning that their order matters and that items can be accessed [and modified] based on their index position. Being able to work with lists and knowing how to remove items is an important skill. For example, you could be building a game where you need to remove items as players select them.

Python provides a number of different methods to remove items from a list. Below, youll find a quick summary of the different methods and how they remove items. In the sections below, youll find in-depth guides as to how these functions work.

MethodWhat it does
list.pop[]Removes an item at an index position and returns it
list.remove[]Removes the first item matching a value
slicingCan be used to delete non-matching ranges of data
del statementRemoves an item at an index position and doesnt return it
list.clear[]Removes all items in a Python list
The many ways to remove an item from a Python list

The Quick Answer: Use pop, remove, and del

Table of Contents

  • Python Remove Method to Remove List Item Based on its Value
  • Python Remove All Items Matching a Value
  • Python Pop Method to Remove a List Item Based on Index Position
  • Python del Method to Remove a List Item Based on Index Position and Dont Return it
  • Remove All Items from a Python List with Clear
  • Remove Items from a Python List with Slicing
  • Removing Items for a Python List Based on a Condition
  • Conclusion

Python Remove Method to Remove List Item Based on its Value

Python makes it easy to delete a list item based on its value by using the Python list remove method. The method scans a list for the first instance of that value and removes the first instance of that value.

Lets see how we can use the .remove[] list method to remove an item from a list:

# Remove a list item by value using .remove[] values = ['datagy', 1, 2, 3, 'datagy'] values.remove[1] print[values] # Returns: ['datagy', 2, 3, 'datagy']

We applied the remove method to our list, in place meaning that we didnt need to reassign the values.

But what happens if we try to remove an item that doesnt exist? Lets see what happens when we try to run the code below:

# Remove a list item by value using .remove[] that doesn't exist values = ['datagy', 1, 2, 3, 'datagy'] values.remove[4] print[values] # Returns: ValueError: list.remove[x]: x not in list

We can see that when we try to use the remove method to remove an item that doesnt exist, then a ValueError is returned. If youre not sure if a value exists in a list and dont want your program to crash, you can wrap the method in a try-except block.

Lets see how we can do that below:

# Remove a list item by value using .remove[] values = ['datagy', 1, 2, 3, 'datagy'] try: values.remove[4] except ValueError: pass print[values] # Returns: ['datagy', 1, 2, 3, 'datagy']

We can see here that when the ValueError is raised that the code skips ahead and does nothing.

In the next section, youll learn how to use the Python remove method to remove all items matching a value.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Python Remove All Items Matching a Value

As shown below, the Python .remove[] method only removes the first instance of that item in a list. What if you wanted to remove all instances of that item in a list? In order to accomplish this, we can use a while loop in order to repeat an action while a statement continues to be true.

In particular, our while loop will continue to remove the item from our list while the item still exists in our list. Lets see how this works in Python:

# Remove all list items by value using .remove[] values = ['datagy', 1, 2, 3, 'datagy'] while 'datagy' in values: values.remove['datagy'] print[values] # Returns: [1, 2, 3]

We can see here that the remove method is applied as many times as the item datagy is still in our list. At that point, the code moves on and prints out the values of our list.

Another way that we can do this is to use a list comprehension. We can have the list comprehension loop over each item in our list see if the item is equal to the item we want to remove. If its not, then we include it in our new list.

Lets see what this looks like in Python:

# Remove all list items by value using .remove[] values = ['datagy', 1, 2, 3, 'datagy'] values = [value for value in values if value != 'datagy'] print[values] # Returns: [1, 2, 3]

In the example above, we looped over each item in our list and included the value if it wasnt equal to the item we wanted to remove.

In the next section, youll learn how to use the Python pop method to remove a list item based on its index position.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Python Pop Method to Remove a List Item Based on Index Position

The Python pop method is a commonly used list method that removes an item from a list and returns it. While the remove method remove an item based on its value, the pop method removes an item based on its index. When you the pop method, we specify the items index and pop it, meaning that we return the item and remove it from the list.

Lets see how this works in Python:

# Remove a list item by position using .pop[] values = ['datagy', 1, 2, 3, 'datagy'] values.pop[0] print[values] # Returns: [1, 2, 3, 'datagy']

We can see that when we pop an item that exists, then the value is removed from the list and is returned.

How do we access the popped item? We can assign it to a value. Lets see how we can do this:

# Remove a list item by index using .pop[] values = ['datagy', 1, 2, 3, 'datagy'] item = values.pop[0] print[item] # Returns: datagy

Lets see what happens when we try to apply the pop method on an item that doesnt exist:

# Remove a list item by index position using pop[] that doesn't exist values = ['datagy', 1, 2, 3, 'datagy'] values.pop[6] print[values] # Returns: IndexError: pop index out of range

We can see that when we try to pop an item that doesnt exist, then we return an IndexError.

In the next section, youll learn how to remove an item using the del method based on a lists index, but dont return it.

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Python del Method to Remove a List Item Based on Index Position and Dont Return it

The Python del operator is similar to the Python pop method, in that it removes a list item based on its position. It differs from the pop method in that the method removes the item but doesnt return it.

The del operator goes further and allows us to delete a slice of items from a list.

Lets see how we can do both of this using the Python del operator:

# Remove list items by value using del values = ['datagy', 1, 2, 3, 'datagy'] del values[0] print[values] # Returns: [1, 2, 3, 'datagy'] values = ['datagy', 1, 2, 3, 'datagy'] del values[1:3] print[values] # Returns: ['datagy', 3, 'datagy']

We can see that in we can both delete a single item or a slice of items from a list in Python.

But what happens when we try to delete an item at a position that doesnt exist? We raise an IndexError. Lets see how this occurs:

# Remove list items by value using del values = ['datagy', 1, 2, 3, 'datagy'] del values[10] print[values] # Returns: IndexError: list assignment index out of range

In the next section, youll learn how to remove all items from a Python list using the clear method.

Want to learn how to use the Python zip[] function to iterate over two lists? This tutorial teaches you exactly what the zip[] function does and shows you some creative ways to use the function.

Remove All Items from a Python List with Clear

There may be times when you want to remove all items from a Python list this is where the .clear[] method comes into play. The clear method works in-place, meaning that we dont need to reassign the list in order to clear it.

Lets see how we can use the clear method to delete all items from a Python list:

# Clear an Entire list in Python values = ['datagy', 1, 2, 3, 'datagy'] values.clear[] print[values] # Returns: []

We can see here when we apply the clear method to a list, that it deletes all items from that list, returning an empty list.

In the next section, youll learn how to remove items from a Python list using slicing.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Remove Items from a Python List with Slicing

We can also remove items from a list by simply slicing the list. The benefit of this approach is that we can reverse the method of using slicing using the del method, by specifying items that we want to keep.

For example, if we wanted to keep all items except for the first and last item, we could write the following:

# Removing list items using slicing values = ['datagy', 1, 2, 3, 'datagy'] values = values[1:-1] print[values] # Returns: IndexError: [1, 2, 3]

Here we re-assign the Python list to a slice of itself, being able to filter items from the slice of itself.

In the next section, youll learn how to use Python to remove items from a list using a condition.

Want to learn how to get a files extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!

Removing Items for a Python List Based on a Condition

In this final section, youll learn how to remove items from a Python list conditionally. For example, you can remove non-numeric items from a list or only delete only odd numbers from a list.

Well accomplish this using a Python list comprehension, which I cover off in detail here. List comprehensions allow us to create new lists by iterating over an iterable object, such as a list.

Lets see how we can use a list comprehension to remove all non-numeric items from our list:

# Delete items from a list conditionally values = ['datagy', 1, 2, 3, 'datagy'] values = [item for item in values if str[item].isdigit[]] print[values] # Returns: [1, 2, 3]

Here we loop over our list and evaluate if the item is a numeric value. If it is, then its added into our list. If its not, then we dont include it.

Similarly, we can delete all odd items from a list using a Python list comprehension:

# Delete items from a list conditionally values = [1, 2, 3, 4, 5, 6] values = [item for item in values if item % 2 == 0] print[values] # Returns: [2, 4, 6]

In the example above, we use the modulus operator to evaluate if an item is even or odd. Any even item, when the modulus 2 is applied, will return a remainder of 0. Similarly, any odd value will return a value of 1. Because of this, we can use the list comprehension to delete any odd numbers from a list.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned how to use Python to delete or remove list items. You learned how to use the pop, del, remove methods to remove items from a list including when to use which method and the pros and cons of each. Finally, you learned how to remove items from a list conditionally in Python, using Python list comprehensions.

To learn more about the Python .remove[] list method, check out the official documentation here.

Share via:

  • Facebook
  • Twitter
  • LinkedIn
  • Email
  • More

Video liên quan

Chủ Đề