setappendjulia

Adding new elements to a Set


How to append a new element to a Set in Julia? For an Array this can be done with append

A = [1, 2, 3] # Array
S = Set(A)    # Set

append!(A, 4) # Works
append!(S, 4) # Does not work

Solution

  • Use push! for an unsorted collection

    julia> S = Set([1, 2, 3])
    Set{Int64} with 3 elements:
      2
      3
      1
    
    julia> push!(S, 4)
    Set{Int64} with 4 elements:
      4
      2
      3
      1