从列表python中删除所有元素

我已经编写了这段代码,但它并没有从列表中删除所有元素,而是只删除了 3 个项目。请检查我做错了什么


names = ["John","Marry","Scala","Micheal","Don"]

if names:

 for name in names:

  print(name)

  print(f"Removing {name} from the list")

  names.remove(name)

print("The list is empty")


慕婉清6462132
浏览 143回答 3
3回答

繁星点点滴滴

要实际就地清除列表,您可以使用以下任何一种方式:alist.clear()  # Python 3.3+, most obviousdel alist[:]alist[:] = []alist *= 0     # fastest并且您的代码的问题是名称必须是names[:] 因为当 for 循环遍历列表时它认为是一个索引号并且当您删除一些索引时您会更改它,因此它会跳过一些索引

呼啦一阵风

names = ["John","Marry","Scala","Micheal","Don"]if names: for name in names[:]:  print(name)  print(f"Removing {name} from the list")  names.remove(name)print("The list is empty")只需在 for 循环中按名称 [:] 分配全名列表JohnRemoving John from the listMarryRemoving Marry from the listScalaRemoving Scala from the listMichealRemoving Micheal from the listDonRemoving Don from the listThe list is empty

鸿蒙传说

只需使用names.clear()它就会清除整个列表
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python