Simple question about assignment to a vector of vectors

Ah yeah this tripped me up at first as well. If you look at the help page for fill:

help?> fill

If x is an object reference, all elements will refer to the same object:

  julia> A = fill(zeros(2), 2);
  
  julia> A[1][1] = 42; # modifies both A[1][1] and A[2][1]
  
  julia> A
  2-element Vector{Vector{Float64}}:
   [42.0, 0.0]
   [42.0, 0.0]

All of the objects in A are the same (like pointing exactly to the same spot in memory). So when you update one, they all get updated.

I usually avoid this using a list comprehension:

julia> B = [zeros(2) for _ in 1:3]
3-element Vector{Vector{Float64}}:
 [0.0, 0.0]
 [0.0, 0.0]
 [0.0, 0.0]

julia> B[1][2] = 5
5

julia> B
3-element Vector{Vector{Float64}}:
 [0.0, 5.0]
 [0.0, 0.0]
 [0.0, 0.0]
4 Likes