# Anonymous functions in for loops

**URL:** <https://discourse.julialang.org/t/anonymous-functions-in-for-loops/81259>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [May 18, 2022, 1:46pm UTC](https://discourse.julialang.org/t/anonymous-functions-in-for-loops/81259 "2022-05-18T13:46:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![domien96](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/domien96/32/36371_2.png) [@domien96](https://discourse.julialang.org/u/domien96)\
**Post date:** [May 18, 2022, 1:46pm UTC](https://discourse.julialang.org/t/anonymous-functions-in-for-loops/81259/1 "2022-05-18T13:46:26Z")

</div>

Why does this code snippet print 2 instead of 1?

```julia
anon = Array{Any}(undef, 2)
for i = 1:2
  anon[i] = ()-> println(i)
  i += 1
end
anon[1]()

```

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [May 18, 2022, 2:01pm UTC](https://discourse.julialang.org/t/anonymous-functions-in-for-loops/81259/2 "2022-05-18T14:01:56Z")

</div>

This is just how closures work. The closure `() -> println(i)` closes over the binding `i`, not just its current value, so it can see changes to that binding. Here’s another example:

```julia
julia> function outer()
         i = 1
         inner = () -> println(i)
         i = 2
         return inner
       end
outer (generic function with 1 method)

julia> f = outer()
#7 (generic function with 1 method)

julia> f()
2

```

Note that this can be confusing because a for-loop introduces a _new_ local variable `i` at each iteration, so if you do:

```julia
julia> fs = []
Any[]

julia> for i in 1:2
         push!(fs, () -> i)
       end

julia> fs[1]()
1

julia> fs[2]()
2

```

then `fs[1]` has captured the variable `i` introduced by the first iteration of the loop, while `fs[2]` has captured the variable `i` introduced by the second iteration of the loop.

If the `i` were the _same_ binding in each iteration of the loop, then you’d get `2` both times due to the `for` loop incrementing `i`. In fact, Python does that, which can be very confusing when you switch between Python and Julia:

```julia
# Python

>>> fs = []
>>> for i in range(1, 3):
... fs.append(lambda: i)                                                                                            
... 
>>> fs[0]()
2
>>> fs[1]()
2

```
