版权声明:偷我的我会气死的, 希望你去访问我的个人主页:https://crazyang.top https://blog.csdn.net/yzy_1996/article/details/88960229
这个问题,你碰不碰得到,你用不用得到,它都在那里
我们先看一段代码
list = ['Google', 'Runoob', 'Taobao', 'Baidu']
for i in list:
print(i)
list.remove(i)
print(list)
我们想要的效果是list里面所有的元素会被删除,最后留下一个空的列表,但实际结果却并不是如此,它的运行结果是:
Google
Taobao
['Runoob', 'Baidu']
究其原因,在删掉第一个值,也就是索引[0]后,索引为[1]的值索引变为了[0],然后第二次删除是从索引[1]开始删除的,所以漏掉了一个值。
如果要用remove函数删空整个List,正确的做法应该是
list = ['Google', 'Runoob', 'Taobao', 'Baidu']
for i in range(len(list)):
list.remove(list[0])
print(list)
输出为:
[]