如果列表大于1,如何从列表中删除项目?

时间:2020-04-23 18:28:10

标签: python

我有一个列表,并且我希望列表只有一个项目长,该怎么做?我曾尝试这样做,但它给了我一个错误:ValueError: list.remove(x): x not in list 这是代码:

List = ["dairy"]
List.append("cheese")

if len(List) > 1:
    List.remove(1)

1 个答案:

答案 0 :(得分:1)

Python的.remove()方法将要删除的值作为参数,因此它将在列表中寻找数字1。要按索引删除,可以使用del或.pop()。例如:

l  = ['dairy']
l.append('cheese')

if len(l) > 1:
     l.pop() # Removes last item in list