append! Vs push! in Julia
Asked Answered
L

1

11

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?

Lophophore answered 8/7, 2022 at 20:37 Comment(2)
related with the #34751725Shirring
@jbytecode, yes, but not the answer to my question! I asked "why do they recommend using push! in these cases?"Lophophore
S
11

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.

Systematize answered 8/7, 2022 at 20:54 Comment(4)
Official doc says "Use push! to add individual items to a collection which are not already themselves in another collection." this means it's recommended to use push! instead of append! in that situation! This is why I intentionally provided those examples to show in those situations, append! works as well! But why are they recommended to use push!? After all, I got your point! Thank you so much!Lophophore
@Systematize please add a comment about untyped containers as otherwise other will use your code to learn Julia and complain how slow it is ;)Overstreet
Sure, I updated the example.Systematize
So essentially append flattens x and y before adding them to a scalar list vGrabble

© 2022 - 2024 — McMap. All rights reserved.