3
$\begingroup$

Im trying to further my understanding of mathematica coding and came up across this question. What is the main difference between Cases and Select?

data = Table[{RandomReal[{-10, 10}], RandomReal[{-10, 10}], RandomReal[{-10, 10}]}, 10^4];
Cases[data, {a_, b_, c_} :> {a, b} /; c > 0]
Select[data, #[[3]] > 0 &][[All, ;; 2]]

Both these approaches give the same result, Im just curious about the benefits of each. When is Select superior to Cases and vice versa.

$\endgroup$

marked as duplicate by Kuba Sep 17 '18 at 17:26

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.

3
$\begingroup$

Cases uses patterns, Select uses testing functions. Because of this, Select is not seldomly faster because it reduces pattern matching to the very least: Does the testing function evaluate to True or not? (Pattern matching can be a real bottleneck sometimes, inparticular if the mere check for matching enforces unpacking of arrays.)

On the other hand, Cases is much more flexible.

1.) Cases allows a level specification. (Select always operates on the first level of an expression)

2.) Cases allows to apply replacement rules immediately.

$\endgroup$
  • $\begingroup$ Thanks @Alan. It was a typo. $\endgroup$ – Henrik Schumacher Sep 17 '18 at 17:27

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