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

Solution 1:

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"]

Solution 2:

Based on the answers here and in Elixir Slack, there are multiple ways to check if an item exists in a list. Per answer by @Gazler:

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

or simply

"foo" in ["foo", "bar"]
# true

or

Enum.any?(["foo", "bar"], &(&1 == "foo")
# true

or if you want to find and return the item instead of true or false

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

If you want to check a tuple, you need to convert to list (credit @Gazler):

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

But as @CaptChrisD pointed out in the comments, this is an uncommon need for a tuple because one usually cares about the exact position of the item in a tuple for pattern matching.

Solution 3:

Or just use in:

iex(1)> "foo" in ["foo", "bar"]
true
iex(2)> "foo" in Tuple.to_list({"foo", "bar"})
true

Solution 4:

I started programming in Elixir yesterday, but I will try something I did a lot in JS, maybe it is useful when the list has a lot of elements and you don't want to traverse it all the time using Enum.member?

map_existence = Enum.reduce(list,%{}, &(Map.put(&2,&1,true)))
map_existence[item_to_check]

You can also retrieve an intersection with some other list:

Enum.filter(some_other_list,&(map_existence[&1]))