4
$\begingroup$

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!

$\endgroup$
5
  • $\begingroup$ It only works for domains, yes. You might be interested in MemberQ[]... $\endgroup$ May 28, 2013 at 14:00
  • $\begingroup$ Thanks. That should do the trick $\endgroup$ May 28, 2013 at 14:03
  • $\begingroup$ You should be able to answer your own question, now... $\endgroup$ May 28, 2013 at 14:04
  • 2
    $\begingroup$ There is an exception to J.M.'s answer: upvalues, although it would only be shorthand for MemberQ[]. $\endgroup$
    – rcollyer
    May 28, 2013 at 14:06
  • 2
    $\begingroup$ Difference is also that Element is a kind of assertion, you tell Mathematica that a given variable belongs to a given domain, whereas MemberQ is a test; you ask Mathematica whether a value is member of a list. $\endgroup$ May 28, 2013 at 20:26

2 Answers 2

4
$\begingroup$

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 *)
$\endgroup$
0
$\begingroup$

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).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.