PythonLists and tuples
list. remove()
Removes the first occurrence of a given value from a list.
- Returns
None- Changes the original
- Yes
Example
#Python
courses = ["HTML", "PHP", "CSS", "PHP"]
courses.remove("PHP")
print(courses)
if "Rust" in courses:
courses.remove("Rust")
print(courses)
print([c for c in courses if c != "PHP"])Resultsaved result, you can check it
['HTML', 'CSS', 'PHP']
['HTML', 'CSS', 'PHP']
['HTML', 'CSS']
Definition and usage
#The remove(x) method looks for an item equal to the given value and removes its first occurrence. Further occurrences stay in the list.
If the value is not in the list, the method raises a ValueError. Before removing it, you can check whether it is present with the in operator, or handle the exception.
To remove by position instead of value, use pop() or the del list[i] statement. You can remove every occurrence with a list comprehension and a condition.
Syntax
#Syntax
list.remove(value)Parameters
#value
any value
The value to remove.
Good practices
#- To remove every occurrence, use a list comprehension, not
remove()in a loop. - Do not remove items from a list while looping over it with a
forloop. You will skip some items.
Related entries
#- list.pop()Removes the item at the given index (the last one by default) and returns it.
- list.clear()Removes all the items from a list.
- list.index()Returns the index of the first occurrence of a value in a list.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
Spotted a mistake or missing an example? Write to us.