# Select a particular rules out of a list

rule = {beta -> 4, alpha -> 2, x -> 4, z -> 2, w -> 0.8}
Select[rule, beta]
Select[rule, beta &]
Select[rule, beta -> _ &]


How would I select the rule that applies to beta only?

Or more general, how to select the rules apply to alpha and beta (or more variable, but not all of them)?

Thanks.

• Closely related: (65892) Feb 9 '16 at 10:35

You can also use FilterRules:

rule = {beta -> 4, alpha -> 2, x -> 4, z -> 2, w -> 0.8};

FilterRules[rule, beta]
(* {beta -> 4} *)

FilterRules[rule, {beta, alpha}]
(* {beta -> 4, alpha -> 2} *)


Update: additional alternatives if you have V10:

KeyTake[rule,{alpha, x}]
(* or *) KeyTake[{alpha,x}][rule]
(* <|alpha->2,x->4|> *)
Normal@KeyTake[rule,{alpha, x}]
(*  {alpha->2,x->4} *)

KeySelect[rule, MatchQ[#,alpha|x]&]
(* or *) KeySelect[MatchQ[#,alpha|x]&][rule]
(* <|alpha->2,x->4|>  *)
Normal@KeySelect[rule, MatchQ[#,alpha|x]&]
(*  {alpha->2,x->4} *)

• Yeah, I certainly need more sleep...
– Kuba
Dec 18 '14 at 16:23
• @Kuba Why? Your method is perfectly adequate. Dec 18 '14 at 17:05
• Nice use of KeyTake. That one isn't in my repertoire yet. Dec 18 '14 at 17:43
• @Mr.Wizard, thank you. Added to my repertoire a minute ago:)
– kglr
Dec 18 '14 at 17:44
• @Mr.Wizard, do we need a similar warning for KeySelect? (I am getting the message "You have exceeded the session memory limit for your plan" when i try to run KeySelect[MatchQ[#,b]&][{a -> b, b -> c, b -> 2}] on the free wolfram programming cloud).
– kglr
Dec 18 '14 at 17:56
Select[rule, MemberQ[{beta, alpha}, #[[1]]] &]


V9 style

If rule is a simple list of rules:

Cases[rule, _[beta | alpha, _]]

{beta -> 4, alpha -> 2}


other ways to go:

{beta, alpha} /. (# -> Rule[##] & @@@ rule)

• First approach is simple to understand. second approach looks more complicated though. Dec 18 '14 at 15:52
• @ChenStatsYu Take a look at (# -> Rule[##] & @@@ rule)
– Kuba
Dec 18 '14 at 15:54
• @kuba I am trying to replicate your first solution as follows: Cases[rule, Rule[beta | alpha, _]] but it did not work. do you know why? this works fine Cases[{{a, 3}, {b, 4}, {c, 5}}, List[a | b, _]] Dec 18 '14 at 16:36
• @Algohi Rule makes Cases think that you want to replace beta|alpha with _. Since by default Cases works on level {1} it can't find anything anyway. To make use of explicitly stated Rule you need HoldPattern[...]
– Kuba
Dec 18 '14 at 16:42

One more method using Pick and Keys:

Pick[rule, Keys@rule, alpha | beta]

{beta -> 4, alpha -> 2}

Rule[#, (Association@rule)[#]] & /@ {beta, alpha}


{beta -> 4, alpha -> 2}