Skip to content

FirstPosition ​

The position of the first occurrence of value, searching every level.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageFirstPosition!
FirstPosition(collection, value)the position of the first occurrence of value, searching every level rather than just the top one.
Typed signatures
TypePackageApplies
(any, any) -> list<integer>combinatoricsalways

Domain: Collections

Details
  • Unlike IndexOf, which only looks at the top level, FirstPosition descends into nested expressions of any head — depth-first, outer to inner, left to right — and matches heads too, at index 00: the first PowerPower in x2+y2x^2 + y^2 is at {1,0}\{1, 0\}. It is Position's first answer.
  • The empty ListList when the value isn't found anywhere.

Examples

Basic #

The first occurrence of bb, nested inside the first sublist

live ↗
InFirstPosition([[a,a,b],[b,a,a],[a,b,a]],b)\mathrm{FirstPosition}(\bigl\lbrack\bigl\lbrack a, a, b\bigr\rbrack, \bigl\lbrack b, a, a\bigr\rbrack, \bigl\lbrack a, b, a\bigr\rbrack\bigr\rbrack, b)Out[1,3]\bigl\lbrack1, 3\bigr\rbrack

The empty list when the value isn't found anywhere

live ↗
InFirstPosition([a,[a,c]],b)\mathrm{FirstPosition}(\bigl\lbrack a, \bigl\lbrack a, c\bigr\rbrack\bigr\rbrack, b)Out[]\bigl\lbrack\bigr\rbrack

Only the earliest of several matches is reported, as a position list

live ↗
InFirstPosition([a,b,a,a,b,c,b],b)\mathrm{FirstPosition}(\bigl\lbrack a, b, a, a, b, c, b\bigr\rbrack, b)Out[2]\bigl\lbrack2\bigr\rbrack
live ↗
InFirstPosition([x,y,z],b)\mathrm{FirstPosition}(\bigl\lbrack x, y, z\bigr\rbrack, b)Out[]\bigl\lbrack\bigr\rbrack
Scope #

Searches nested lists and returns the full multi-level position

live ↗
InFirstPosition([[1,2],[2,3],[3,1]],3)\mathrm{FirstPosition}(\bigl\lbrack\bigl\lbrack1, 2\bigr\rbrack, \bigl\lbrack2, 3\bigr\rbrack, \bigl\lbrack3, 1\bigr\rbrack\bigr\rbrack, 3)Out[2,2]\bigl\lbrack2, 2\bigr\rbrack
live ↗
InFirstPosition(x2+y2,Power)\mathrm{FirstPosition}(x^2+y^2, \mathrm{Power})Out[1,0]\bigl\lbrack1, 0\bigr\rbrack
Properties #

A match nested inside an earlier sublist beats a plain match later at the top level: depth-first, outer to inner, left to right

live ↗
InFirstPosition([a,[a,b],b],b)\mathrm{FirstPosition}(\bigl\lbrack a, \bigl\lbrack a, b\bigr\rbrack, b\bigr\rbrack, b)Out[2,2]\bigl\lbrack2, 2\bigr\rbrack

Repeated matches later in the list are ignored once one is found at the front

live ↗
InFirstPosition([a,b,b,a,a,c],a)\mathrm{FirstPosition}(\bigl\lbrack a, b, b, a, a, c\bigr\rbrack, a)Out[1]\bigl\lbrack1\bigr\rbrack
About
Examples8
Checked againstWolfram Language 6 agree2 differ
CrosswalkWolfram Language

See also: IndexOf, Position, At