David Sainez
David Sainez

Reputation: 6976

How can I determine if an array contains some element?

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?

Upvotes: 8

Views: 13436

Answers (1)

David Sainez
David Sainez

Reputation: 6976

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

Upvotes: 17

Related Questions