Could Someone Guide me on Issue with Array Indexing in Julia?

Hello there,

This is my code:
Julia code demonstrating the issue
x = [1, 2, 3, 4, 5]
y = x[1:3]

Now let’s try to modify y
y[1] = 10

println("x: ", x)
println("y: ", y)

I am encountering an unexpected behavior while working with array indexing in Julia. In the code snippet above, I’m trying to create a new array y by indexing elements 1 to 3 from array x. However, when I modify an element of y, I notice that the corresponding element in x is also modified, which is unexpected behavior to me.

I would expect x to remain unchanged after modifying y.

Also, I have gone through this: https://discourse.julialang.org/t/please-someone-explain-me-the-array-indexing-example-from-manual/110174devops which definitely helped me out a lot

Could someone please explain why this is happening and suggest how I can achieve my desired behavior?

Thankyou in advance for your help and assistance.

This shouldn’t happen, and doesn’t happen for me.

x = [1, 2, 3, 4, 5]
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> y = x[1:3]
3-element Vector{Int64}:
 1
 2
 3

julia> y[1] = 10
10

julia> x
5-element Vector{Int64}:
 1
 2
 3
 4
 5

To get the behaviour you describe usually requires either a y = x assignment, or using the @view/@views macro (or view function).

1 Like