Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Removing by Value: remove()

The method pop() removes an element by its position. Often, though, you know what you want to remove, not where it is. For that, lists have the method remove(): you write a value in the parentheses, and it removes the element with that value:

guests = ["Anna", "Tom", "Lucy", "Max"]
guests.remove("Tom")
print(guests)

This prints:

['Anna', 'Lucy', 'Max']

If the value is in the list more than once, remove() removes only the first one, counted from the start:

numbers = [3, 7, 3, 9]
numbers.remove(3)
print(numbers)

This prints:

[7, 3, 9]

Unlike pop(), remove() doesn't return the removed element. You already know its value, after all.

If the value isn't in the list at all, the program stops with an error. Text is compared exactly, so "tom" with a lowercase t isn't the same as "Tom":

guests = ["Anna", "Tom", "Lucy"]
guests.remove("tom")

The program ends with this error:

Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: list.remove(x): x not in list

ValueError is an error with a value. Here, x stands for the value you wanted to remove, and not in list says that it isn't in the list. In the next exercise, you'll learn how to check first whether a value is in a list.

Instructions

  1. 1

    The weather forecast says it won't rain. Remove "umbrella" from the list packing with remove().

  2. 2

    Print packing. The output should be ['passport', 'sunscreen', 'sunglasses'].

Back

8/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.