Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Consider the two seemingly closely related operations:

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; x == f]
(* {g[x], h[x]} *)    
DeleteCases[{f[x], g[x], h[x]}, x_[_] /; x != f]
(* {f[x], g[x], h[x]} *)    

The first case gives the desired result of removing f[x], while the second doesn't work properly (I would expect to get back only f[x] in that case). However, the only difference between the two is the use of a != as opposed to a ==. Is this a bug or is there a good reason for this behavior?

Note: Interestingly, even Not[Equal[x,f]] doesn't fix the problem (while Equal[x,f] does work).

share|improve this question

marked as duplicate by Mr.Wizard Jun 18 at 18:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Not sure quite what is going (I'm pretty sure it's relatively straight-forward), but consider doing the following: DeleteCases[{f[x], g[x], h[x]}, x_[_] /; (x =!= f)]. Also, DeleteCases[{f[x], g[x], h[x]}, _f] and Cases[{f[x], g[x], h[x]}, _f]. – march Mar 12 at 3:43
4  
For comparisons like yours, you really should be using ===/=!= instead of ==/!=. – J. M. Mar 12 at 3:57
up vote 10 down vote accepted

Even Equal doesn't work, although it seems to work. What you expect is a comparison, that gives True when two symbols are the same and False otherwise. Look at this:

f == g
(* f == g *)

This is surely not what you expect. While it seems OK in your first example, because f==f indeed simplifies to True, the flaw becomes obvious in your second example:

g != f
(* g != f *)

Mathematica tries to decide whether f and g are unequal. The problem is that unequal is not equivalent to they are not the same. So the rule of thumb is, if you do numeric comparisons, then you often want to use == or != except you are comparing exact numbers. If you want to decide whether expressions are the same or not, then you need to use === or =!=.

Here are some examples as a brain teaser:

1 === 1.0
(* False *)

1 == 1.0
(* True *)
share|improve this answer

Something "ugly" also:

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; TrueQ[x == f]]

(*{g[x], h[x]}*)

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; !TrueQ[x == f]]

(*{f[x]}*)
share|improve this answer

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