# Mutating a Set during iteration

**URL:** https://discourse.julialang.org/t/mutating-a-set-during-iteration/30558
**Category:** New to Julia
**Tags:** question
**Created:** [October 31, 2019, 7:55pm UTC](https://discourse.julialang.org/t/mutating-a-set-during-iteration/30558 "2019-10-31T19:55:05Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)
#### Post date: [October 31, 2019, 7:55pm UTC](https://discourse.julialang.org/t/mutating-a-set-during-iteration/30558/1 "2019-10-31T19:55:05Z")

</div>

Is it safe to iterate over a set and mutate it in process?  
Say, I have a `Set{Int64}` and want to replace all negative values in it by their absolute values. Is it OK to

```julia
for x in set_of_ints
    if x < 0
        pop!(set_of_ints, x)
        push!(set_of_ints, -x)
    end
end

```

?

---

<div class="post-metadata">

### Author: ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)
#### Post date: [October 31, 2019, 8:25pm UTC](https://discourse.julialang.org/t/mutating-a-set-during-iteration/30558/2 "2019-10-31T20:25:39Z")

</div>

The answer is that it often works, but not always. Also it is bad practice to mutate a collection while iterating and should be avoided. You can generate counter examples like this:

```julia
using Test
for _ in 1:1000
    set_of_ints = Set(rand(-1000:1000, 2000))
    s2 = deepcopy(set_of_ints)
    
    for x in set_of_ints
        if x < 0
            pop!(set_of_ints, x)
            push!(set_of_ints, -x)
        end
    end
    @test set_of_ints == Set(map(abs, collect(s2)))
end

```

---

<div class="post-metadata">

### Author: ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)
#### Post date: [October 31, 2019, 8:50pm UTC](https://discourse.julialang.org/t/mutating-a-set-during-iteration/30558/3 "2019-10-31T20:50:47Z")

</div>

Thanks, I suspected that this pattern working for me once was accidental. `replace!` seems to be the proper way to do that.
