How to check whether an term is an element of a list in Elixir

Is it possible to check whether a term is an element of a list in Elixir ?

You can use: 3 in [1, 2, 3] (documented here)

Alternatively: Enum.member?([1, 2, 3], 3) (documented here)

The first way also works in guards.

4 Likes

But only if the list is a literal list, you can’t use a variable. 3 in a is not possible in a guard.

3 Likes

And what if I want to check whether it is part of a list and then do a case statement to check further more what to do with sub elements ?

So you want to check if something is a strict sublist of a list? Or if lists intersect if interpreted as a set? Or any other setting I don’t see right now? I think you’ll have to go a bit more into detail here.

What have you tried so far? Where did you get stuck?

3 Likes

The thing is that I wish to check whether a term is an element of a list, using nested ifs. If yes then I need to do some pattern matching, but that’s ok.

I have tried the solutions presented previously in the same thread, and I think that it is working just fine. More specifically I used :

Enum.member?([1, 2, 3], 3)

If that solved your problem, you could mark it as the solution, so it can be useful to others with the same question. EDIT: I just saw this was posted in discussions and not in questions. Maybe next time it’s better to post it in questions.

Regarding the nested pattern matching, it is often good practice to try to unnest it for better readability. There are a few options, depending on the specific case.

If the list you want to test membership of is a literal, you can extract your logic in a function with guards:

def my_function(element) when element in [1, 2, 3] do
  # your nested logic here
end

def my_function(_) do
  # handle case when element is not in the list
end

If you need to do nested pattern matching, and want to “short circuit” as soon as any match fails, you can use with/1.

1 Like