Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if an array contains some element?

Tags:

julia

How can I tell if an array contains some element?

I have been manually checking with a loop:

for x in xs
    if x == a
        return true
    end
end
return false

Is there a more idiomatic way?

like image 851
David Varela Avatar asked Dec 31 '22 09:12

David Varela


1 Answers

The in operator will iterate over an array and check if some element exists:

julia> xs = [5, 9, 2, 3, 3, 8, 7]

julia> 8 in xs
true

julia> 1 in xs
false

It is important to remember that missing values can alter the behavior you might otherwise expect:

julia> 2 in [1, missing]
missing

in can be used on general collections. In particular, matrices:

julia> A = [1 4 7
            2 5 8
            3 6 9]
3×3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9

julia> 7 in A
true

julia> 10 in A
false
like image 100
David Varela Avatar answered Feb 19 '23 12:02

David Varela