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?
Dot calls correspond to the broadcast function in Julia.
In Julia, arrays are actually mutable type collections which are used for lists, vectors, tables, and matrices. That is why the values of arrays in Julia can be modified with the use of certain pre-defined keywords.
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.
Edit:
As noted by @SalchiPapa and @DNF in the comments, you can do !(6 in a)
if you prefer to avoid Unicode characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With