julia

append! Vs push! in Julia


In Julia, you can permanently append elements to an existing vector using append! or push!. For example:

julia> vec = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

julia> push!(vec, 4,5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

# or

julia> append!(vec, 4,5)
7-element Vector{Int64}:
 1
 2
 3
 4
 5

But, what is the difference between append! and push!? According to the official doc it's recommended to:

"Use push! to add individual items to a collection which are not already themselves in another collection. The result of the preceding example is equivalent to push!([1, 2, 3], 4, 5, 6)."

So this is the main difference between these two functions! But, in the example above, I appended individual elements to an existing vector using append!. So why do they recommend using push! in these cases?


Solution

  • append!(v, x) will iterate x, and essentially push! the elements of x to v. push!(v, x) will take x as a whole and add it at the end of v. In your example there is no difference, since in Julia you can iterate a number (it behaves like an iterator with length 1). Here is a better example illustrating the difference:

    julia> v = Any[]; # Intentionally using Any just to show the difference
    
    julia> x = [1, 2, 3]; y = [4, 5, 6];
    
    julia> push!(v, x, y);
    
    julia> append!(v, x, y);
    
    julia> v
    8-element Vector{Any}:
      [1, 2, 3]
      [4, 5, 6]
     1
     2
     3
     4
     5
     6
    

    In this example, when using push!, x and y becomes elements of v, but when using append! the elements of x and y become elements of v.