Python remove陷阱
给出下面代码,先思考一下会输出什么
list_a = [1, 2, 3, 4, 5]
for i in list_a:
list_a.remove(i)
print(list_a)
[2, 4]
为什么会输出这个结果呢
我们可以增加一行打印分析一下情况
list_a = [1, 2, 3, 4, 5]
for i in list_a:
print(f'the index of {i} in the {list_a} is {list_a.index(i)}')
list_a.remove(i)
print(list_a)
the index of 1 in the [1, 2, 3, 4, 5] is 0
the index of 3 in the [2, 3, 4, 5] is 1
the index of 5 in the [2, 4, 5] is 2
[2, 4]
我们可以看到,for循环对列表元素进行遍历时,会按照索引进行遍历
当执行第二次循环时,也就是列表变为 [2, 3, 4, 5],读取到的i为3,可见是按照索引进行遍历的,后续的分析也同理。
这也说明列表是一个可变的数据
【todo】:后续对源代码分析