julia

Is there an elegant way to do "not in" in Julia?


I am trying to convert a python script to Julia. I am checking to make sure I am doing this code in the most optimal way. Please see the following code:

julia> a = [1,2,3,4,5]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> if 1 in a
           print("1 is in a")
       end
1 is in a
julia> if 6 not in a
           print("6 not in a")
       end
ERROR: TypeError: non-boolean (Int64) used in boolean context
Stacktrace:
 [1] top-level scope at REPL[6]:1

julia> push!(a, 6)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
julia> if (6 in a) == true
           print("6 in a")
       end
6 not in a
julia> b = [1]
1-element Array{Int64,1}:
 1

julia> if (6 in b) == true
           print("6 in b")
       end


Am I doing this "not in" check correctly?


Solution

  • julia> a = [1, 2, 3, 4, 5];
    
    julia> 6 ∉ a
    true
    

    The symbol can be typed in the REPL by typing \notin and then hitting TAB. Of course, the symbol is also available as an alternative to in by typing \in and hitting TAB:

    julia> 6 ∈ a
    false
    

    Sometimes you need a vectorized version:

    julia> x = [2, 7];
    
    julia> x .∉ Ref(a)
    2-element BitArray{1}:
     0
     1
    

    The Ref is needed in this case so that a is treated as a scalar in the broadcasting operation.

    If you prefer to avoid Unicode characters, you can write !(6 in a) instead of 6 ∉ a.