Is it defined behavior to modify `iter` while `for`-looping over it?

WalterMadelim
Thu, 18 Sep 2025 07:20:42 +0000
New to Julia

Since the docstring of for is very concise, I cannot fathom one thing—as the title suggests.

for i = iter
    # body
end

I have learned that i is local and different among passes.
For example, iter = 1:3, then we have 3 passes: i = 1, i = 2, i = 3. The three i here are all local, but they are mutually different objects despite they are all named i from the programmer’s view. This is good.

I think the iter part is decided once before the first pass starts. For example, this code has clear intention:

for i = shuffle(1:7)
    println(i)
end

Clearly we want to shuffle 1:7 once and print the result—we certainly do not intend to shuffle 1:7 every time i is updated (we do not intend to shuffle seven times)

Therefore I think the spirit of the for is:

do not re-evaluate iter every time i is updated to the next pass

Now the question is: am I sane to write this code?

function steal!(v)
    for _ = 1:5
        sleep(1)
        popfirst!(v)
        popfirst!(v)
        popfirst!(v)
    end
end;
function test()
    v = collect(1:30)
    Threads.@spawn steal!(v)
    for i = v
        println(i)
        sleep(0.6)
    end
end;

Threads.nthreads() # 7
test() # does this make some sense?

Is this defined behavior? Will it be useful in practice?

33 posts - 5 participants