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

**URL:** <https://discourse.julialang.org/t/is-it-defined-behavior-to-modify-iter-while-for-looping-over-it/132477>\
**Category:** New to Julia\
**Tags:** question, for-loop\
**Created:** [September 18, 2025, 7:20am UTC](https://discourse.julialang.org/t/is-it-defined-behavior-to-modify-iter-while-for-looping-over-it/132477 "2025-09-18T07:20:42Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![eldee](https://avatars.discourse-cdn.com/v4/letter/e/b5a626/32.png) [@eldee](https://discourse.julialang.org/u/eldee)\
**Post date:** [September 18, 2025, 12:38pm UTC](https://discourse.julialang.org/t/is-it-defined-behavior-to-modify-iter-while-for-looping-over-it/132477/20 "2025-09-18T12:38:37Z")

</div>

> [@WalterMadelim](#):
>
> I have learned that `i` is local and different among passes.

I don’t think this is necessarily true (depending on how you define difference). For example, if you want to produce `collect(1:k)` for all `k <= n` for a given `n`, you could use

```julia
struct S
    n::Int
end

Base.iterate(s::S) = iterate(s, Int[])
function Base.iterate(s::S, state)
    length(state) >= s.n && return nothing
    push!(state, length(state) + 1)
    return state, state
end

Base.length(s::S) = s.n

```

Then indeed

```julia-repl
julia> s = S(3)
S(3)

julia> for i in s
           println(i)
       end
[1]
[1, 2]
[1, 2, 3]

```

but

```julia-auto
julia> collect(s)
3-element Vector{Any}:
 [1, 2, 3]
 [1, 2, 3]
 [1, 2, 3]

```

as all `i` point to the same `Vector`.

Of course, this is a silly example, but I can imagine that in certain situations you might want to mutate the returned `item`/`state` in-place for performance reasons. In this case this should definitely be clearly documented. To be fully safe

> [@foobar\_lv2](#):
>
> you simply need to look up the implementations of the respective `iterate` functions.

---

_[View the full topic](https://discourse.julialang.org/t/is-it-defined-behavior-to-modify-iter-while-for-looping-over-it/132477)._
