Course Content
Python Data Structures
Python Data Structures
The remove() Method
The remove()
method deletes the first occurrence of a specific value in the list. This is particularly useful when you know the element's value but not its index.
The syntax of remove()
method is:
Now, you decide to remove "Kyoto" from your list because you've already visited it. Here's how you can do it:
travel_wishlist = ["Paris", "Oslo", "Kyoto", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # Output: ['Paris', 'Oslo', 'Sydney']
If "Kyoto" isn't on the list, this code will raise an error.
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # ValueError: list.remove(x): x not in list
To avoid this, you can check if the city exists before removing it:
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] if "Kyoto" in travel_wishlist: travel_wishlist.remove("Kyoto") print(travel_wishlist)
Note
With the
remove()
method, you can only take out one item at a time.
Swipe to show code editor
You changed your mind about one of the cities. Use the remove()
method to delete Oslo
from the travel_wishlist
.
Thanks for your feedback!
The remove() Method
The remove()
method deletes the first occurrence of a specific value in the list. This is particularly useful when you know the element's value but not its index.
The syntax of remove()
method is:
Now, you decide to remove "Kyoto" from your list because you've already visited it. Here's how you can do it:
travel_wishlist = ["Paris", "Oslo", "Kyoto", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # Output: ['Paris', 'Oslo', 'Sydney']
If "Kyoto" isn't on the list, this code will raise an error.
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # ValueError: list.remove(x): x not in list
To avoid this, you can check if the city exists before removing it:
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] if "Kyoto" in travel_wishlist: travel_wishlist.remove("Kyoto") print(travel_wishlist)
Note
With the
remove()
method, you can only take out one item at a time.
Swipe to show code editor
You changed your mind about one of the cities. Use the remove()
method to delete Oslo
from the travel_wishlist
.
Thanks for your feedback!