4
$\begingroup$
lst = {a, b, c}
DeleteCases[lst, a]

Delete one specific element a.

How do I delete elements a and c?

DeleteCases[lst, a || c]
(* does not work *)

How to I delete more than one (specific) elements efficiently?

$\endgroup$
6
  • 2
    $\begingroup$ One | too much :) a|c. $\endgroup$
    – Kuba
    Jan 20, 2015 at 21:30
  • 2
    $\begingroup$ Yup, as Kuba and soandos pointed out, pattern-matching uses |, whereas Boolean expressions use ||. You can read more at guide/Patterns, which contains a list of most of the pattern-matching syntax that is commonly used. It may seem weird that they use different syntax, but in Mathematica, expressions are considered different objects than patterns. Unlike expressions, which are used all the time, patterns are not commonly encountered by beginning users, and are strange to learn about at first (I'm still getting used to them), but they can sometimes be useful. $\endgroup$ Jan 20, 2015 at 21:35
  • 1
    $\begingroup$ @DumpsterDoofus I have mislead by the useless help files many times. Wolfram should really consider using some of the examples here, which are far more useful than its own examples. $\endgroup$ Jan 20, 2015 at 21:39
  • 3
    $\begingroup$ More generally, given a list A and b, you could get the elements of A that aren't in b using either Complement[A, b] or DeleteCases[A, Alternatives @@ b]. $\endgroup$ Jan 20, 2015 at 21:40
  • 1
    $\begingroup$ There is a large chapter on patterns in the documentaion. One of its sections deals with patterns involving alternatives. $\endgroup$ Jan 20, 2015 at 22:06

1 Answer 1

7
$\begingroup$

You can use Alternatives:

DeleteCases[lst, a|c]
$\endgroup$
4
  • $\begingroup$ That's just what I thought. But why || does not represent OR in this case? $\endgroup$ Jan 20, 2015 at 21:32
  • 2
    $\begingroup$ @ChenStatsYu It does. The problem is that a||b is not a pattern object. Its not even a function, and so DeleteCases doesn't know what to do with it $\endgroup$
    – soandos
    Jan 20, 2015 at 21:34
  • $\begingroup$ @soandos, a||c is a perfectly legitimate pattern. DeleteCases treats it just like any other pattern, e.g. DeleteCases[{a || c, a && c}, a || c] $\endgroup$ Jan 20, 2015 at 21:38
  • $\begingroup$ @SimonWoods I think I mean that in the context of a pattern object, the || and && are not evaluated $\endgroup$
    – soandos
    Jan 20, 2015 at 21:39

Your Answer

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

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