copy
copy(x)
Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
Examples
-
Create a copy of an array:
julia> arr = [1, 2, 3, 4, 5]; julia> arr_copy = copy(arr); julia> arr_copy[1] = 10; julia> arr 5-element Array{Int64,1}: 1 2 3 4 5 julia> arr_copy 5-element Array{Int64,1}: 10 2 3 4 5This example demonstrates that modifying the copied array (
arr_copy) does not affect the original array (arr). -
Copy a dictionary:
julia> dict = Dict("a" => 1, "b" => 2, "c" => 3); julia> dict_copy = copy(dict); julia> dict_copy["b"] = 20; julia> dict Dict{String,Int64} with 3 entries: "a" => 1 "b" => 2 "c" => 3 julia> dict_copy Dict{String,Int64} with 3 entries: "a" => 1 "b" => 20 "c" => 3Here, the copied dictionary (
dict_copy) can be modified independently without affecting the original dictionary (dict). - Copy a string:
julia> str = "Hello, Julia!"; julia> str_copy = copy(str); julia> str_copy[1] = 'J'; julia> str "Hello, Julia!" julia> str_copy "Jello, Julia!"In this example, copying a string allows you to modify the copied string without modifying the original string.
Common mistake example:
julia> a = [1, 2, 3];
julia> b = a;
julia> c = copy(a);
julia> b[1] = 10;
julia> c[1] = 20;
julia> a
3-element Array{Int64,1}:
10
2
3
julia> b
3-element Array{Int64,1}:
10
2
3
julia> c
3-element Array{Int64,1}:
20
2
3
In this example, assigning b = a creates a reference to the original array, so modifying b also modifies a. However, using copy(a) creates a new array c that is independent of a.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.