python循环设定次数_For循环迭代的次数少于Python

本文解释了在Python中使用for循环删除列表元素时,循环为何会提前终止。原因是每次删除第一个元素时,迭代器的指针会跳过已删除的元素,导致迭代次数少于预期。解决方案是避免在遍历过程中修改列表,或者使用列表副本进行操作。
摘要由CSDN通过智能技术生成

I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior.

I understand that the list changes as I delete elements but I don't get how that affects the for loop condition.

Why is the loop iterating less than six times?

a = [1, 2, 3, 4, 5, 6]

for elem in a:

del a[0]

print(a)

解决方案

You are deleting the first element in every iteration of the loop by del a[0], so the iterator is emptied in 3 steps, because it moves to the element after the one you removed on the next iteration.

You can check the element the iterator is currently on, and the list status in the code below

a = [1, 2, 3, 4, 5, 6]

for elem in a:

print(elem)

del a[0]

print(a)

The output is

1

[2, 3, 4, 5, 6]

3

[3, 4, 5, 6]

5

[4, 5, 6]

You can think of it as a pointer pointing to the first element of the list, that pointer jumps 2 steps when you delete the first element on each iteration, and it can jump only 3 times for 6 elements.

Generally it is a bad idea to modify the same list you are iterating on.

But if you really want to, you can iterate over the copy of the list a[:] if you really want to delete items

a = [1, 2, 3, 4, 5, 6]

for elem in a[:]:

del a[0]

print(a)

The output is

[2, 3, 4, 5, 6]

[3, 4, 5, 6]

[4, 5, 6]

[5, 6]

[6]

[]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值