如果列表中没有某个元素,则您无法从该列表中删除该元素,否则会出现 Python 错误 ValueError: list.remove(x): x not in list 。
在此,我们将讨论 ValueError 的原因:list.remove(x): x not in list。我们还将讨论如何解决此错误。
ValueError: list.remove(x): x not in list Python 错误告诉我们我们正在使用 remove() 方法删除未出现在列表中的元素。让我们看一个错误的例子。
我们编写一个程序,让老师知道谁提交了作业。为此,我们建立一个学生的列表。如果学生交了作业,他的名字将从列表中删除。
students = ["LiMing", "WangJing", "ZhaoTao"]
to_remove = input("请输入完成作业的学生姓名: ")
students.remove(to_remove)
print("该学生的作业已被记录。")
让我们尝试运行程序:
请输入完成作业的学生姓名: xiaoli
我们的程序返回:
Traceback (most recent call last):
File "D:/Python38/1.py", line 5, in <module> students.remove(to_remove)
ValueError: list.remove(x): x not in list
程序出现错误,因为xiaoli没有出现在我们的列表中。
解决方案
为了解决这个错误,我们应该首先检查我们要从列表中删除的学生是否出现在列表中:
if to_remove in students:
students.remove(to_remove)
print("该学生的作业已被记录。")
else:
print("这个学生没有出现在你的名单中。")
再次运行代码:
请输入完成作业的学生姓名: xiaoli
这个学生没有出现在你的名单中。
我们的代码现在返回一条消息而不是 Python 错误。
结论
ValueError: list.remove(x): x not in list 当您尝试从列表中删除未出现在列表中的项目时会发生。您使用 remove() 方法删除不存在的项目才能显示此错误消息。
要解决该错误,您应该首先检查要删除的项目是否存在列表中。