Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Elia Pellegrini
The Python "ValueError: list.remove(x): x not in list" occurs when we call the
remove()
method with a value that does not exist in the list. To solve the
error, check if the value exists in the list before removing it, or use a
try/except
block.
Here is an example of how the error occurs.
my_list = ['apple', 'banana', 'kiwi'] # ⛔️ ValueError: list.remove(x): x not in list my_list.remove('melon')
We passed a value that is not in the list to the remove()
method which caused
the error.
One way to solve the error is to check if the value is present in the list
before passing it to the remove()
method.
my_list = ['apple', 'banana', 'kiwi'] if 'melon' in my_list: my_list.remove('melon') print(my_list) else: # 👇️ this runs print('value is not in the list')
The
in operator
operator tests for membership. For example, x in l
evaluates to True
if x
is a member of l
, otherwise it evaluates to False
.
If you use a for
loop, make sure to iterate over a copy of the list if you
need to remove any items.
my_list = ['apple', 'banana', 'kiwi'] # ✅ iterate over copy for i in my_list.copy(): my_list.remove(i) print(my_list) # 👉️ []
We used the copy()
method to create a shallow copy of the list when iterating.
The list.remove() method removes the first item from the list whose value is equal to the passed in argument.
my_list = ['a', 'b', 'c'] my_list.remove('a') print(my_list) # 👉️ ['b', 'c']
The method raises a ValueError
if there is no such item.
The remove()
method mutates the original list and returns None
.
You can also use a try/except
statement to handle the error in case the value
is not present in the list.
my_list = ['a', 'b', 'c'] try: my_list.remove('r') except ValueError: print('Item not in list') print(my_list) # 👉️ ['a', 'b', 'c']
We call the remove()
method on the list and if a ValueError
is raised, the
except
block is ran.
If you have a two-dimensional list, make sure you are calling the remove()
method on the correct list.
my_list = [['a', 'b'], ['c', 'd']] my_list[0].remove('b') print(my_list) # 👉️ [['a'], ['c', 'd']]
We accessed the list item at index 0
and called the remove()
method on it.
Had we called the remove()
method on the outer list, we would get a
ValueError
because it doesn't contain the string "b"
.