Why x[[1,2]] = [0,0] works?

question

#1

Why this works:

julia> x = collect(1:5);

julia> x[[1,2]] = [0,0]
2-element Array{Int64,1}:
0
0

julia> x
5-element Array{Int64,1}:
0
0
3
4
5

I thought x[[1,2]] = [0,0] should be a syntax error (the correct syntax being x[[1,2]] .= [0,0].

So what is going on when I type x[[1,2]] = [0,0]? Is it different from x[[1,2]] .= [0,0]?


#2

In an expression of the form x[i]=y, the left-hand side x[i] is not evaluated first. Instead, it is interpreted as Base.setindex!(x,y,i). This is not unique to Julia: Matlab and Python basically do the same.

On the other hand, x[i].=y becomes broadcast!(identity,view(x,i),y), and more generally x[i] .= f.(y) is broadcast!(f,view(x,i),y) etc.
This is different, since, e.g., x[1:2] .= 1 broadcasts 1 into the index’s shape, whereas x[1:2] = 1 is an error.
Also, if you do x[i] = f.(y) you are asking for a temporary array f.(y), whereas x[i] .= f.(y) is an in-place computation.


#3

Thanks for the detailed reply!