ValueError: list.remove(x): x not in list
In this article, we will learn about the error ValueError: list.remove(x): x not in list.
This error is generated when we try to remove a list item that is not present in the list while using the remove( ) method.
remove() method is a built-in method available in python that removes the items of the list.
Let us understand it more with the help of an example.
Example:
# Creating a list MyList
MyList = ["India", "USA", "UK"]
# Removing 'Russia' from MyList
MyList.remove("Russia")
# Printing MyList
print(MyList)
Output:
File "list.py", line 5, in <module>
MyList.remove("Russia")
ValueError: list.remove(x): x not in list
In the above example, in line 5 of the code, we are trying to remove a list item. That does not exist in the list thus causing the error “ValueError: list.remove(x): x not in list”.
Solution:
To check whether the item exist or not in the list use in keyword. As shown in the example below.
Example:
# Creating a list MyList
MyList = ["India", "USA", "UK"]
# Check if "Russia" present in list item
if "Russia" in MyList:
# Remove "Russia" from MyList
MyList.remove("Russia")
else:
print("Russia does not exist in the list")
# Printing MyList
print(MyList)
Output:
Russia does not exist in the list
['India', 'USA', 'UK']
The above code will first check whether or if “Russia” exist in the list or not. If it exists the remove( ) method will remove it from the list and print the updated list.
If it does not the code will print “Russia does not exist in the list” and print the original list.