You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从嵌套内层for循环中递增外层for循环的变量?

Why modifying the outer loop's i inside the inner loop doesn't work as expected

Hey there! Let me walk you through what's going on with your code and how to fix it.

First, let's recap your code and the unexpected behavior you ran into:

Your code:

x = [0,1,2,3,4,5,6,7,8,9,10]
for i in x:
    print(x[i])
    for j in x:
        i += 1

You expected incrementing i inside the inner for j loop would make the outer loop skip ahead, but instead you ended up with output like i:0; x[i]:0 i:1; x[i]:1 ... i:5; x[i]:5 — not what you wanted at all.

The root cause

Here's the key thing about Python's for...in loops: the loop variable (i in your case) gets reassigned on every iteration directly from the iterable you're looping over (which is x here). When you do i +=1 inside the inner loop, you're only changing the value of that i variable right then. But as soon as the inner loop finishes and the outer loop starts its next iteration, Python will grab the next element from x and assign it to i — completely overwriting the changes you made inside the inner loop.

In short: your inner loop's increments are being ignored by the outer loop, because the outer loop doesn't care about the current value of i — it just pulls the next item from x each time.

The fix

If you want full control over how i increments (including letting the inner loop alter it), swap the outer for loop for a while loop. With while, you manage the i variable yourself, so any changes you make to it (even inside the inner loop) will stick.

Here's how that would look:

x = [0,1,2,3,4,5,6,7,8,9,10]
i = 0
while i < len(x):
    print(f"i:{i}; x[i]:{x[i]}")
    for j in x:
        i += 1
        # Add a check to avoid index errors if i goes beyond the list length
        if i >= len(x):
            break

Now, every time you increment i in the inner loop, the outer while loop will use that updated value to check if it should keep running. This way, your inner loop's changes to i actually affect the outer loop's behavior, just like you intended.

内容的提问来源于stack exchange,提问作者Nilesh Ingle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:15