Select

Select

Select[ Hold[x -> cond], expr ] returns all parts of an expression that satisfy a condition.

Usages

Select[ Hold[x -> cond], expr ]

Select checks the condition cond for expr itself and for all its parts, at every level, and returns a list of the parts for which the condition is not False. The condition is written as a mapping inside Hold, so that it is checked for each part separately.

Example in out
The roots in an expression. Select[ Hold[x -> Type[x] == Sqrt], 2 Sqrt[3] + Sqrt[5] ] {Sqrt[3], Sqrt[5]}
The variables in an expression. Select[ Hold[x -> Type[x] == Variable], 2x + 3y ] {x, y}
The integers in an expression, at all levels: the exponent 2 is found too. Select[ Hold[x -> Type[x] == NaturalNumber], 2x^2 + 3x + 6 ] {2, 2, 3, 6}
The integers in a list. Select[ Hold[x -> Type[x] == NaturalNumber], {1, a, 3, 2.5} ] {1, 3}
Options

Recursive

If set to False, only the direct parts of expr are checked, such as the elements of a list. Default: True.

Syntax Example out
Select[ Hold[x -> cond], expr, Recursive=>False ] Select[ Hold[x -> x >> 2], {1, 3, 5}, Recursive=>False ] {3, 5}

ByIndex

If set to True, the positions of the parts are returned instead of the parts. Each position is a list of indices, one for each level. Default: False.

Syntax Example out
Select[ Hold[x -> cond], expr, ByIndex=>True ] Select[ Hold[x -> Type[x] == NaturalNumber], {1, a, 3}, ByIndex=>True, Recursive=>False ] { {1}, {3} }
Warning
  • Always put the mapping in Hold. Without it, the condition is evaluated too early: Select[ x -> Type[x] == NaturalNumber, {1, a, 3, 2.5}, Recursive=>False ] gives {}.
  • With the default Recursive=>True, expr itself is also checked. A comparison applied to a whole list is usually not False, so Select[ Hold[x -> x >> 2], {1, 3, 5} ] returns { {1, 3, 5} }: the whole list. Use Recursive=>False to select elements of a list.

See also: SelectI, Type, Map