29

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?

1 Answer 1

44
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.

2
  • 7
    Sometimes displaying Unicode will be a problem, depending on your setup, you can also just negate the whole expression like this: x = [1, 2, 3]; 2 in x, !(2 in x) # (true, false) Jan 30, 2020 at 5:30
  • 3
    There is an open issue requesting to use ! in front of infix operators: github.com/JuliaLang/julia/issues/25512 In that case you could write 6 !in a. It doesn't appear to be going anywhere, though. For now, it's best to use !(6 in a) I think.
    – DNF
    Jan 30, 2020 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.