3
$\begingroup$

Replace[x, {{x -> a}, {x -> b},{y->c}}] gives {a,b,x}. How to get just {a,b} from the above expression?

$\endgroup$
3
$\begingroup$

I assume you're trying to use this for a more general case. Knowing what the general case is would help me know which solution would be generalizable to your situation.

One way is to use ReplaceList with Flatten:

Flatten[ReplaceList[x, {{x -> a}, {x -> b}, {y -> c}}]]

Or more simply:

ReplaceList[x, {x -> a, x -> b, y -> c}]
$\endgroup$
2
$\begingroup$

Add an extra replacement to each list such that if nothing matches you return Nothing

nullrep = _ :> Nothing
(* _ :> Nothing *)

Replace[x, {{x -> a, nullrep}, {x -> b, nullrep}, {y -> c, nullrep}}]
(* {a, b} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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