# Strange behavior of setindex() inside a function or a loop?

**URL:** <https://discourse.julialang.org/t/strange-behavior-of-setindex-inside-a-function-or-a-loop/29042>\
**Category:** General Usage\
**Tags:** question\
**Created:** [September 22, 2019, 2:12pm UTC](https://discourse.julialang.org/t/strange-behavior-of-setindex-inside-a-function-or-a-loop/29042 "2019-09-22T14:12:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [September 22, 2019, 2:12pm UTC](https://discourse.julialang.org/t/strange-behavior-of-setindex-inside-a-function-or-a-loop/29042/1 "2019-09-22T14:12:18Z")

</div>

I’m not sure if this is a known issue or I’ve missed something obvious, but the following functions didn’t work as I expected. `f()` works correctly without a return value, but once I add `return tt` I get the original tuple without any values changed. The same happens if `setindex` is used inside a loop.

```julia
julia> using StaticArrays

julia> function f()
           tt = ntuple(_->0,10)
           setindex(tt,50,2)
       end
f (generic function with 1 method)

julia> f()
(0, 50, 0, 0, 0, 0, 0, 0, 0, 0)

julia> function f2()
           tt = ntuple(_->0,10)
           setindex(tt,50,2)
           tt
       end
f2 (generic function with 1 method)

julia> f2()
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

julia> function f3()
           tt = ntuple(_->0,10)
           for i = 1:length(tt)
               setindex(tt,i,i)
           end
           tt
       end
f3 (generic function with 1 method)

julia> f3()
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

```

---

<div class="post-metadata">

**Author:** ![BeastyBlacksmith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/beastyblacksmith/32/4741_2.png) [@BeastyBlacksmith](https://discourse.julialang.org/u/BeastyBlacksmith)\
**Post date:** [September 22, 2019, 2:18pm UTC](https://discourse.julialang.org/t/strange-behavior-of-setindex-inside-a-function-or-a-loop/29042/2 "2019-09-22T14:18:06Z")

</div>

Tuples are immutable and hence `tt` is always a tuple of zeros in your examples.  
The first function did return the return value of `setindex`, since it was the last executed statement of function, which is another tuple with a `50` at index `2`.  
If you want `tt` to be that tuple, you have to assign it like

```julia
tt = setindex(tt, 50, 2)

```

---

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [September 22, 2019, 2:28pm UTC](https://discourse.julialang.org/t/strange-behavior-of-setindex-inside-a-function-or-a-loop/29042/3 "2019-09-22T14:28:04Z")

</div>

Makes sense, thank you.
