Which
Details
- Which has attribute HoldAll.
- If any of the testi evaluated by Which give neither True nor False, then a Which object containing these remaining elements is returned unevaluated. »
- You can make Which return a "default value" by taking the last testi to be True.
- If all the testi evaluate to False, Which returns Null.
Examples
open all close allBasic Examples (1)
a = 2;Which[a == 1, x, a == 2, b]Scope (4)
Programming Behavior (3)
Which can be maintained in symbolic form:
Which[a == 1, x, a == 2, b]% /. a -> 2Conditions are evaluated until one is found that is neither True nor False:
Which[1 < 0, a,
x == 0, b,
0 < 1, c]Use True for an else clause that always matches:
sign[x_] := Which[
x < 0, -1,
x > 0, 1,
True, Indeterminate]sign /@ {-2, 0, 3}Symbolic Transformations (1)
f = Which[x < -Pi / 2, -1, -Pi / 2 ≤ x ≤ Pi / 2, Sin[x], True, 1]Expand it to use Piecewise:
PiecewiseExpand[f]Reduce[f == 1 / 2, x]Integrate[f, {x, 0, 3}]D[f, x]Plot[f, {x, -Pi, Pi}]Properties & Relations (2)
Use Which rather than a nested if-then-elseif chain:
cut1[x_] := If[x < -1, -1, If[x < 1, x, 1]]cut1 /@ {-2, -1, 0, 1, 2}cut2[x_] := Which[
x < -1, -1,
x < 1, x,
True, 1]cut2 /@ {-2, -1, 0, 1, 2}Use PiecewiseExpand to convert Which to Piecewise:
PiecewiseExpand[Which[c1, a1, c2, a2, True, a3]]PiecewiseExpand[Which[c1, Which[d1, b1, True, b2], True, a2]]PiecewiseExpand[Which[Which[d1, b1, True, b2], a1, True, a2]]Tech Notes
Related Guides
History
Introduced in 1988 (1.0)
Text
Wolfram Research (1988), Which, Wolfram Language function, https://reference.wolfram.com/language/ref/Which.html.
CMS
Wolfram Language. 1988. "Which." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/Which.html.
APA
Wolfram Language. (1988). Which. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Which.html
BibTeX
@misc{reference.wolfram_2026_which, author="Wolfram Research", title="{Which}", year="1988", howpublished="\url{https://reference.wolfram.com/language/ref/Which.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_which, organization={Wolfram Research}, title={Which}, year={1988}, url={https://reference.wolfram.com/language/ref/Which.html}, note=[Accessed: 13-June-2026]}