fill(anArray,2) behaviour

I have doubts about the usefulness of fill(anArray,2). The use case for the current behaviour seems limited (who needs 2 copies of the same array in an array?) and the potential for being misleading is considerable (falsely assuming that these two arrays can be independently changed).

Still, I admit that there might be reasons of internal logic for this behaviour. If so, I suggest a careful documentation. (Yes…I fell into this trap today. )


X = fill(zeros(2),2)
X[1][1] = 99


2-element Array{Array{Float64,1},1}:
 [99.0, 0.0]
 [99.0, 0.0]

I felt into this trap in the past as well. To get different arrays you can do:

[zeros(2) for i in 1:2]
1 Like

The reason is simply that is is precisely the same as the behavior of

X[1] = y
X[2] = y

combined with the fact that julia does not implicitly copy things.

I agree that this can be confusing at first, but, to be fair, this exact issue is already specifically outlined in the documentation of fill(), so I’m not sure how much more documentation is really needed.

In a perfect world, I might have chosen a more descriptive name (would “repeat” be better?).


[zeros(2) for i in 1:2]

Thanks. That is indeed the way to do it.

this exact issue is already specifically outlined in the documentation of fill() ,

I believe the documentation says If x is an object reference, all elements will refer to the same object. I must admit that this was not entirely easy for me to parse.

If someone wants to improve that documentation, it would be helpful to give an example like the one in your original post here.


Fair enough. I’ll read up on how to do that (no, I don’t know) and then give it a try.