Position with test for list of lists
The documentation for Position provides the answer:
The default level specification for Position is {0,Infinity}, with Heads->True.
You're not setting Heads -> False, so Position will look at:
Level[{{8, 7}, {10, 8}, {6, 10}, {3, 2}, {9, 8}, {0, 1}, {2, 1},
{1, 10}, {6, 8}, {5, 9}}, 1, Heads -> True]
Which is:
{List, {8, 7}, {10, 8}, {6, 10}, {3, 2}, {9, 8}, {0, 1}, {2, 1}, {1, 10}, {6, 8}, {5, 9}}
You're then asking Position to take #[[1]]
, i.e. List[[1]]
... Error!
This works:
RandomInteger[10, {10, 2}]
Position[%, _?(#[[1]] > 5 &), {1}, Heads -> False]
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 byn
indices.A negative level
-n
consists of all parts of expr with depthn
.
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.