Is it worth introducing `copy()` into learnxiny?

Many new users use: Learn Julia in Y Minutes
New users coming from Matlab/Octave (like myself) may not realize that using = w/ arrays does not create a new copy.

a1 = [1:5;]
a2 = a1
a2[5] = a2[5] +40
a2 
a1
#
a1 = [1:5;]
a2 = copy(a1)
a2[5] = a2[5] +40
a2 
a1

This is @ChrisRackauckas Gotcha #5: Views, Copy, and Deepcopy

Is this worth adding?

2 Likes

Sure–it’s an important part of Julia, but it’s probably worth being clear that this has nothing to do with arrays in particular; rather it is a property of how = works with everything in Julia. In fairness, though, new users will often first experience this in the context of an array just because they are so widely used.

Something like:

# Assignment with `=` attaches a new label to the same value without copying
a = [1, 2, 3]
b = a
# Now `b` and `a` point to the same value, so changing one affects the other:
a[3] = 5
b[3]  # => 5

# The `copy()` function can create a shallow copy of an array, dictionary,
# or other container
a = [1, 2, 3]
c = copy(a)
a[3] = 5
c[3] # => 3

might be a nice addition.

2 Likes

Thanks.
Should this go under:

1. Primitive Datatypes and Operators

or

2. Variables and Collections

or somewhere else
I’m reluctant to use my own judgement bc alot of ppl use this tutorial…

I’d say probably (2), but I’d be interested if other people have opinions too.

Put it under (2) for now, else I’ll forget.
Tagged @rdeits & linked to here.
If someone has a better idea, we can improve it later