How to check if an item exists in an Elixir list or tuple?

ewH picture ewH · Apr 5, 2016 · Viewed 53.4k times · Source

This is seemingly simple, but I can't seem to find it in the docs. I need to simply return true or false if an item exists in a list or tuple. Is Enum.find/3 really the best way to do this?

Enum.find(["foo", "bar"], &(&1 == "foo")) != nil

Answer

Gazler picture Gazler · Apr 5, 2016

You can use Enum.member?/2

Enum.member?(["foo", "bar"], "foo")
# true

With a tuple you will want to convert to to a list first using Tuple.to_list/1

Tuple.to_list({"foo", "bar"})
# ["foo", "bar"]