setdiff

setdiff(s1,s2)

Construct the set of elements in s1 but not s2. Maintains order with arrays. Note that both arguments must be collections, and both will be iterated over. In particular, setdiff(set,element) where element is a potential member of set, will not work in general.

Examples

julia> setdiff(Set(1,2,3,4),Set(2,3,5))
Set{Int64}({4,1})
julia> setdiff(Set(2,3),Set(2,3))
Set{Int64}({})
julia> all = [10:-1:1];
julia> odd = [1:2:10];

julia> even = setdiff(all, odd)     # note the ordering of elements in result
5-element Array{Int64,1}:
 10
  8
  6
  4
  2
  1. Find the set difference between two arrays:

    julia> setdiff([1, 2, 3, 4, 5], [3, 4, 5, 6, 7])
    2-element Array{Int64,1}:
    1
    2

    This example returns an array of elements that are present in the first array but not in the second array.

  2. Handle set differences between vectors of strings:

    julia> setdiff(["apple", "banana", "orange", "grape"], ["banana", "grape"])
    2-element Array{String,1}:
    "apple"
    "orange"

    It returns a vector of strings with elements that are present in the first vector but not in the second vector.

  3. Maintain the order of elements with arrays:
    julia> setdiff([5, 10, 15, 20, 25], [10, 20])
    3-element Array{Int64,1}:
    5
    15
    25

    The order of elements is preserved in the resulting array.

Common mistake example:

julia> setdiff([1, 2, 3], 2)
ERROR: MethodError: no method matching setdiff(::Array{Int64,1}, ::Int64)

In this example, the second argument is not a collection. Remember that both arguments to setdiff must be collections. Ensure that both s1 and s2 are valid collections to avoid such errors.

See Also

complement, complement!, intersect, intersect!, issubset, selectperm, selectperm!, Set, setdiff, setdiff!, symdiff, union, union!,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: