# Wrong order in push! operator

Hi,
I have a problem using the push! operator. It seems that it does not push the next elements at the end of the arrays. Can someone confirm my result:

``````using Distributions

e = 1 * 10^(-2)
n_data = 2

x = rand(Uniform(-e, e), n_data, 1)
y = rand(Uniform(-e, e), n_data, 1)
z = rand(Uniform(-e, e), n_data, 1)

vec1 = []
vec2 = []

for xi in x
a = zeros(3)
a = xi
for yi in y
a = yi
for zi in z
a = zi
b = 2 * a
push!(vec1, a)
push!(vec2, b)

end
end
end

println(vec1)
println(vec2)
``````

The output I get is :

[-0.007628929670578818, -0.007324861395442884, 0.003913249936206481]
[-0.015257859341157635, -0.015167500156704537, -0.014534791007813352]

which is not corresponding with b = 2*a.

The problem is that the vector `a` is mutated in the two inner loops (only the outermost loop creates a new vector every time). Consider the following example:

``````julia> v = [];

julia> a = [1,2,3];

julia> push!(v, a)
1-element Array{Any,1}:
[1, 2, 3]

julia> a = 100
100

julia> push!(v, a)
2-element Array{Any,1}:
[1, 2, 100]
[1, 2, 100]
``````
3 Likes

See this post on push!

2 Likes