Can the Element[] function only be used for the domains given in the documentation? I am trying to use it to determine if a value is contained in a previously defined list. Thanks!
2 Answers
There are as usual several ways. The most convenient one is probably MemberQ
, as already pointed out in the comments.
MemberQ[{1, 2, 3, 4, 9}, 9]
(* True *)
If you have a complex structure and not only a flat list, then FreeQ
can be of use. Note that you have to negate the result.
MemberQ[{1, 2, {3}, {{4, 9}}}, 9]
Not[FreeQ[{1, 2, {3}, {{4, 9}}}, 9]]
(* False *)
(* True *)
Finally, note that you can specify the level where MemberQ
should look for the appearance of the element
MemberQ[{1, 2, {3}, {{4, 9}}}, 9, Infinity]
(* True *)
I have not tested it, but this dirty hack might be pretty fast IF you have to assess membership in a list of symbolic values with no zeros.
symMemberQ[x_, mylist_] := SameQ[Times @@ Flatten[mylist /. x -> 0], 0]
Adding Flatten wil take care of nested list.
symMemberQ[e, {a, {b, g}, {d, {e, f}}}]
True
symMemberQ[w, {a, {b, g}, {d, {e, f}}}]
False
(It's a dirty hack, so beware: it might bite you).
MemberQ[]
... $\endgroup$MemberQ[]
. $\endgroup$