How to Remove Items From Lists in Python

How to Remove Items From Lists in Python

by Dorothy Phoenix Dec 23, 2024 basics python

Removing items from a Python list is a common task that you can accomplish with various techniques. Whether you need to remove an item by its position or value, Python has you covered. In this tutorial, you’ll explore different approaches to removing items from a list, including using .pop(), the del statement, and .remove().

The .remove() method allows you to delete the first occurrence of a specified value, while .pop() can remove an item by its index and return it. The del statement offers another way to remove items by index, and you can also use it to delete slices of a list. The approach you choose will depend on your specific needs.

By the end of this tutorial, you’ll understand that:

  • To remove an item from a list in Python, you can use various approaches like .pop(), del, .remove(), and .clear().
  • To remove items from a certain position in a list, you use the .pop() method.
  • To delete items and slices from a list in Python, you use the del statement.
  • You use the .remove() method to delete the first occurrence of a specified value from a list.
  • To remove all the items from a list, you use .clear().
  • You can also remove duplicate items using a loop, dictionary, or set.

To get the most out of this tutorial, you should be familiar with basic Python list topics like creating lists, adding items to a list, and accessing items in a list.

Take the Quiz: Test your knowledge with our interactive “How to Remove Items From Lists in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Remove Items From Lists in Python

In this quiz, you'll test your understanding of removing items from lists in Python. This is a fundamental skill in Python programming, and mastering it will enable you to manipulate lists effectively.

How to Remove Specific Items From a List

One common operation you’ll perform on a Python list is to remove specific list items. You may need to remove items based on their position in the list, or their value.

To illustrate how you can accomplish this task, suppose you’re creating a website for a public library. Your web app will allow users to save a list of books they would like to read. It should also allow them to edit and remove books from the list, as well as sort the list.

You can use a Python list to store the user’s reading list as a collection of book titles. For example, the reading list might look something like this:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]

Now that you have a list of books, you have several ways to remove a single, specific book from the list. One approach is to use the .pop() method.

Removing Items Using the .pop() Method

Sometimes, you may need to remove items at a certain position in a list. For example, in a public library app, users might select books to remove by ticking checkboxes in the user interface. Your app will delete each selected item based on its index, which is the item’s position in the list.

If you know the index of the item you want to remove, then you can use the .pop() method. This method takes the item’s index as an optional argument and then removes and returns the item at that index. If you don’t pass an index argument to the method call, then .pop() will remove and return the last item in the list.

Note that Python lists use zero-based indexing for positioning, which means that the first element in a list is at index 0, the second element is at index 1, and so on. With that in mind, here’s an example of how you can use .pop() to remove and display the first element in your books list:

Python
>>> books.pop(0)
'Dragonsbane'

You invoke the .pop() method on the books list with an index of 0, indicating the first element in the list. This call removes the first title, Dragonsbane, from the list and then returns it.

If you check the content of your list after running this code, then you’ll notice that Dragonsbane isn’t there anymore:

Python
>>> books
['The Hobbit', 'Wonder', 'Jaws']

Here, you display the book list again after the .pop() call. You can see that your list is now one element shorter because .pop() removed the first title.

As you learned earlier in the tutorial, .pop() removes an item and also returns its value, which you can then use for other operations. For example, suppose the library app also allows users to store a separate list of books they’ve read. Once the user has read a book, they can remove it from the initial book list and transfer the title to the read list:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> read_books = []

>>> read = books.pop(0)
>>> read_books.append(read)

>>> read_books
['Dragonsbane']
>>> books
['The Hobbit', 'Wonder', 'Jaws']

On the second line in the example, you create a new, empty list called read_books to store the names of the books the user has read. Next, you use the .pop() method to remove the first title from the original book list and store it in a variable. Then, you use .append() to add the stored title to the read_books list.

When you inspect the contents of both lists, you see that the read list now includes the first removed title, and the original book list no longer contains the title.

If you call the .pop() method on an empty list, the method will raise an IndexError exception:

Python
>>> books.pop()
'Jaws'
>>> books.pop()
'Wonder'
>>> books.pop()
'The Hobbit'

>>> books.pop()
Traceback (most recent call last):
  ...
IndexError: pop from empty list

In this example, you call .pop() on your list repeatedly, removing each title in the list. Your final call to .pop() results in an IndexError exception because you’re calling the method on an empty list.

The .pop() method will also raise an IndexError if you call it with an index argument that’s larger than the list size minus one:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> books.pop(50)
Traceback (most recent call last):
  ...
IndexError: pop index out of range

In this code snippet, you call .pop() on the original book list, which only contains four elements. You used the .pop() method for the item at index 50, but this is out of range because the list isn’t that big, so it raises an IndexError.

Using a negative index as the argument to .pop() allows you to remove list items from right to left, rather than starting from the beginning of the list. For example, a -1 index accesses the last item in the list, a -2 index will access the second to last item, and so on. According to this pattern, books[-len(books)] is a negative index that returns the first item.

The following example shows how to use a negative index with .pop() to remove the last item from a list::

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> books.pop(-1)
'Jaws'

>>> books
['Dragonsbane', 'The Hobbit', 'Wonder']

You call .pop() on the list using -1 as an argument. That index removes the final title, Jaws, from the list. When you check the list’s contents again, you can see that the last item has been removed. You could also have called books.pop() without an argument to get the same effect.

Deleting Items With the del Statement

You can also remove items from a specific index with the del statement. Like the .pop() method, del removes an item at the given position, but it doesn’t return the value.

To illustrate, say that the user of your public library app has accidentally added some books to the list twice. The following example shows how to properly use del to remove the duplicate book titles:

Python
>>> >>> books = [
...     "Dragonsbane",
...     "The Hobbit",
...     "Wonder",
...     "Wonder",
...     "Jaws",
...     "Jaws",
... ]

>>> del books[2]
>>> books
['Dragonsbane', 'The Hobbit', 'Wonder', 'Jaws', 'Jaws']

In the highlighted line, you first write the del keyword, then your list variable name, followed by the desired index in square brackets.

Just like with the .pop() method, you can also use negative index values with the del statement to remove items from the end of a list:

Python
>>> del books[-1]

You remove the last item in the list with the del statement, but it won’t return the value. If you need to store the removed value for any reason, then use the .pop() method instead.

Similar to the .pop() method, you’ll get an IndexError exception if you attempt to use del on a list with an invalid index:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> del books[100]
Traceback (most recent call last):
  ...
IndexError: list assignment index out of range

The book list contains only four items, but you attempt to execute del on the list using an index of 100. This index is out of range because there’s no item at position 100.

Unlike .pop(), you must provide an index value with a del statement. If you don’t, then the program will raise a SyntaxError:

Python
>>> del books[]
  File "<input>", line 1
    del books[]
              ^
SyntaxError: invalid syntax

You execute the del statement without an index, which results in a SyntaxError exception because the indexing operator requires a target index. This statement doesn’t delete the last item in the list as calling .pop() without an argument does.

Removing Items by Value With the .remove() Method

Suppose that the book list app provides a text field where users can enter a title to delete from the list.

If you want to remove an item from a list by its value rather than by its index, you can use the .remove() method. It requires a single value as an argument, and removes the first item in the list that matches that value:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> books.remove("The Hobbit")
>>> books
['Dragonsbane', 'Wonder', 'Jaws']

On the second line of this example, you call .remove() to remove The Hobbit from the list of books. When you display the updated list, you see that The Hobbit has been successfully removed.

If you call .remove() with a value that isn’t in the list, the method will raise a ValueError exception, as shown in the following code:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> books.remove("The Two Towers")
Traceback (most recent call last):
  ...
ValueError: list.remove(x): x not in list

Also, unlike .pop(), you can’t call .remove() without passing in a value:

Python
>>> books.remove()
Traceback (most recent call last):
  ...
TypeError: list.remove() takes exactly one argument (0 given)

Here, you call .remove() without passing it an argument. As a result, you receive a TypeError message explaining that the method requires an argument.

Delete a Portion of a List

Your user may need to remove several items from a list at once. Say that your public library app displays a certain number of items per page, similar to an email service or a shopping site, and it allows the user to select and delete all of the items on that page at once.

If the list shows 25 items per page, it’d be quicker for the user to remove all 25 items together as a chunk, rather than clicking on and deleting each one individually.

You can do this type of deletion with the del statement, which you used earlier to remove items from a specific index. The del statement also lets you delete slices of the list at once, so instead of providing a single index argument, you pass an inclusive start position and an exclusive end position, separated by a colon.

The del statement then removes all items in the list that are within that index range. For example, suppose you want to remove the first three books from the list:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
>>> del books[0:3]
>>> books
['Jaws']

In the second line, you invoke the del statement call that deletes the list slice. Then, you display the updated list, which shows that the first three items have been deleted. Remember, the index values start at index 0 and go up to but don’t include index 3. So in the code, you removed the first three titles from the list.

You can also use negative index values with del to delete a range of list items, as shown in the example below:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws", "It"]
>>> del books[-3:-1]
>>> books
['Dragonsbane', 'The Hobbit', 'It']

In this example, on the second line, you delete the books starting from index -3 (the Wonder entry), and up to, but not including the item at index -1 (It). Remember, with negative indices, you count the items backwards from the end of the list. For example, the del books[-3:-1] statement is equivalent to del books[2:4] in this case.

Clear All Items From a List

Suppose your user wants to completely clear the book list. You can remove all items from a list using the .clear() method. Here’s how it works:

Python
>>> books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws", "It"]
>>> books.clear()
>>> books
[]

In the first line, you call the .clear() method, which takes no arguments and removes all items from the list. You then inspect books in the Python shell after the .clear() operation, which confirms that the list is now empty.

Remove Duplicates With a Loop

Suppose you’re working on an app that allows duplicate entries in a list. For example, a contact book app might allow multiple contacts with the same phone number but different names. In this case, you may encounter a list with duplicate phone numbers.

To remove duplicates from the list, you can use a combination of loops and list methods. This approach involves iterating through the list and removing each instance of a value when there’s more than one occurrence of that value.

Earlier, you saw how the .remove() method only removes the first instance of an item that matches the value argument. Now, you’ll see how you can use it in a loop.

For simplicity, imagine your contact book app is used in a country with short phone numbers that include an initial two-digit country code. Also, suppose that the order of the numbers in the list is important. Your contact list might look something like this:

Python
>>> phone_numbers = ["54123", "54123", "54456", "54789", "54789", "54123"]

First, you need to determine how many times a number appears in the list. Python provides the .count() method, which returns the number of occurrences of a specified value in the list.

For example, you can use .count() to determine how many times the number 54123 appears in the contact list:

Python
>>> phone_numbers.count("54123")
3

The call to .count() returns 3, letting you know how many instances of the phone number are in the list. Next, it’s time to create the loop to remove the duplicates. You can create a loop that checks to see if there’s more than one instance of the number and then removes each duplicate until only one number is left.

Using the .count() method and a loop, you can iterate through the contact list, and for each number, as long as the count is greater than one, remove one of the instances:

Python
>>> phone_numbers = ["54123", "54123", "54456", "54789", "54789", "54123"]

>>> for phone_number in phone_numbers[:]:
...     while phone_numbers.count(phone_number) > 1:
...         phone_numbers.remove(phone_number)
...

>>> phone_numbers
['54456', '54789', '54123']

In this example, you see the list of phone numbers with duplicates. On the second line, you set up a for loop that will look at each number, one at a time. While the count for a number is greater than one, you call .remove() on the list with the number as an argument. After the loop finishes, you’ll have a list without any duplicates. Note that the ordering in the final list is based on the last occurance of each item.

For a more concise way to remove duplicates, you can also use a dictionary. A dictionary is a Python data type that represents an associative collection of unique keys that are mapped to values. Since dictionaries can’t contain duplicate keys, you can use the .fromkeys() method to remove copies from your list:

Python
>>> phone_numbers = ["54123", "54123", "54456", "54789", "54789", "54123"]

>>> phone_numbers = list(dict.fromkeys(phone_numbers))

>>> phone_numbers
['54123', '54456', '54789']

You use the .fromkeys() method to convert your list to a dictionary without duplicate keys. Then, you convert the dictionary back to a list that now has the duplicates removed. Dictionaries keep their insertion order, so you’re guaranteed that elements in your deduplicated list is ordered like in the original. With this method, the final order corresponds to the ordering of the first occurance of each item.

Use a Set to Remove Duplicates

In the earlier contact book example, the order of the numbers in the list mattered. However, if you want to remove duplicate items in a list and don’t care about the order of the items, then consider using a set instead of a list. A set is a built-in collection type in Python that doesn’t allow duplicate items.

The example below shows how you can convert a list into a set of unique phone numbers:

Python
>>> phone_numbers = ["54123", "54123", "54456", "54789", "54789", "54123"]

>>> set(phone_numbers)
{'54123', '54789', '54456'}

On the highlighted line, you use set() to convert the list into a set, removing all duplicate entries. Note that sets are unordered collections, so they don’t guarantee that your list items will be arranged in their original order. Because of this behavior, a set may not be the right data type to use if your project requires the items to remain ordered.

However, sets can be sorted into a list, which is often an important requirement for contact lists and other such apps. They also support efficient membership testing, allowing you to quickly check whether a value exists in the collection.

Conclusion

You’ve learned various techniques for removing items from a Python list, whether by position or value. You explored methods like .pop(), .remove(), and .clear(). You also learned about the del statement. Each of these tools offers a unique approach to list manipulation. Additionally, you delved into removing duplicates using other approaches, such as loops, dictionaries, and sets.

Learning about list manipulation is essential for a Python developer, as lists are a fundamental data type in Python.

In this tutorial, you’ve learned how to:

  • Remove an item from a list by index using .pop() and del
  • Use the .remove() method to delete the first occurrence of a specified value
  • Delete slices or portions from a list with the del statement
  • Clear all items from a list using the .clear() method
  • Remove duplicate items with a loop, dictionary, or set

These skills will allow you to manipulate lists efficiently in your Python projects, making your code more robust and adaptable to various data handling needs.

Frequently Asked Questions

Now that you have some experience with removing items from lists in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer:

You can remove an item by its index using the .pop() method or the del statement. The .pop() method removes and returns the item at the specified index, while del only removes the item without returning it.

The .remove() method deletes the first occurrence of a specified value from a list, while .pop() removes and returns an item at a specified index.

You can delete multiple items from a list at once using the del statement with a slice, specifying the start and end indices of the range you want to remove.

You can use the .clear() method to remove all items from a list, leaving it empty.

You can remove duplicates by converting the list to a dictionary with dict.fromkeys(), using a loop with .remove(), or converting the list to a set if preserving the order isn’t important.

Take the Quiz: Test your knowledge with our interactive “How to Remove Items From Lists in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Remove Items From Lists in Python

In this quiz, you'll test your understanding of removing items from lists in Python. This is a fundamental skill in Python programming, and mastering it will enable you to manipulate lists effectively.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Dorothy Phoenix

Dorothy is an independent video game developer, software engineer, technical writer, and tutor.

» More about Dorothy

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!