I think there are two more lines from Position documentation might be relevant for the OP.
A positive level n
consists of all parts of expr specified by n
indices.
A negative level -n
consists of all parts of expr with depth n
.
So, for the OP task this code works even with default Heads->True
:
list = RandomInteger[10, {10, 2}];
Position[list, _?(#[[1]] > 5 &), {-2}]
To see why it happens let's make a toy list, ls = {{a,b},{c,d}}
.
Position[ls, _, {1}]
(* {{0}, {1}, {2}} *)
We may see, that all positions have one index inside {}
. Heads included (they have 0
as one of indeces).
Position[ls, _, {2}]
(* {{1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}} *)
We may see, that all positions have two indeces inside {}
. Heads included.
On the contrary, negative levelspecs work in a different way in Position
:
Position[ls, _, {-2}]
(* {{1}, {2}} *)
These are positions of elements with Depth[..]==2
; let's check this:
MapAt[Depth[#] &, ls, Position[ls, _, {-2}]]
(* {2, 2} *)
As a footnote, this statement gives different result (note the head 1
):
MapAt[Depth[#] &, ls, Position[ls, _, {1}]]
(* 1[2,2] *)
Finally,
Position[ls, _, {-1}]
(* {{0}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}} *)
These are positions of elements with Depth[..]==1
; let's check:
MapAt[Depth[#] &, ls, Position[ls, _, {-1}]]
(* 1[1[1, 1], 1[1, 1]] *)
We may see all 1
(including Heads
).
One has to be careful with more complex cases of nested lists.
Position[list, _, {-2}]
andPosition[list, _, {1}]
are different $\endgroup$Position[%, _?(And[Depth[#] > 1, #[[1]] > 5] &), {1}]
$\endgroup$Depth
etc., but onlyPosition[%, _[__]?(#[[1]] > 5 &), {1}]
. If one is willing to modify the test function itself this can be written more cleanly asPosition[%, _[x_, ___] /; x > 5, {1}]
. $\endgroup$