How to Find the First Instance of a Value in an Array

Hi all,

I was wondering why this wasn’t working:

mylist = ["a", "b", "c"]
findfirst(["a"], mylist)

As I expected it to work in at least Julia 1.6. Instead I got a stacktrace that looked like this:

ERROR: MethodError: no method matching findfirst(::Vector{String}, ::Vector{String})
Closest candidates are:
  findfirst(::Function, ::Union{AbstractString, AbstractArray}) at array.jl:1906
  findfirst(::Function, ::Any) at array.jl:1898
  findfirst(::AbstractArray) at array.jl:1824
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[22]:1

~ tcp :deciduous_tree:

1 Like

Instead, thanks to @mcabbott and @jling, I discovered this is the syntax I wanted:

findfirst(==("a"), mylist)

which returns 1 as expected. The following syntax is a bit more expressive and easier to read:

findall(x -> x == "a", mylist)
6 Likes

Or

findfirst(isequal("a"), mylist)

Is clear too.

2 Likes

findfirst(mylist .== "a") is quite easy to read as well.

1 Like

Its easy to read, but it creates intermediate array (i.e. allocates) and as such it is slower than other versions.

2 Likes

Agree, thank you.