# Finding positions of sublists matching a criterion

I want to find in a list of couples the positions of the ones with consecutive items:

z={{1, 2}, {2, 3}, {3, 6}, {6, 7}, {7, 10}, {10, 11}, {11, 14}, {14, 19}, {19, 20}, {20, 25}, {25, 28}, {28, 29}, {29, 32}, {32, 37}, {37, 42}, {42, 43}, {43, 48}, {48, 51}, {51, 52}, {52, 57}, {57, 60}, {60, 65}, {65, 72}, {72, 75}, {75, 76}, {76, 79}, {79, 80}, {80, 83}, {83, 96}, {96, 99}, {99, 104}, {104, 105}, {105, 114}, {114, 115}, {115, 120}, {120, 125}, {125, 128}, {128, 133}, {133, 138}, {138, 139}, {139, 148}, {148, 149}, {149, 152}, {152, 153}, {153, 164}, {164, 175}, {175, 178}, {178, 179}}
Flatten@Position[z, _?(#[[2]] == #[[1]] + 1 &)]


I have used this previously but strangely I get:

Part::partd: Part specification List[[2]] is longer than depth of object.
Part::partd: Part specification List[[2]] is longer than depth of object.
Part::partd: Part specification List[[2]] is longer than depth of object.
General::stop: Further output of Part::partd will be suppressed during this calculation.

{1, 2, 4, 6, 9, 12, 16, 19, 25, 27, 32, 34, 40, 42, 44, 48}


The answer is correct but I don't understand the messages above.

• Try: Position[z, {x_, y_} /; y == x + 1] Mar 24, 2023 at 9:24
• Try Position[z, _?(Function[Echo[#];#[[2]] == #[[1]] + 1])] to see where the messages come from. Mar 24, 2023 at 11:28
• Try: Position[z, x_List /; Last[x] == First[x] + 1] Mar 24, 2023 at 14:49
• Also {z[[All,1]]+1, z[[All,2]]}//Transpose//MapApply[Subtract]//Position[0] Mar 24, 2023 at 17:05

The following will solve your problem:

Flatten@Position[z, _?(#[[2]] == #[[1]] + 1 &), {1}, Heads -> False]


The more idiomatic solution has been written by Daniel Huber in the comments. Building on that:

Position[z, {a_Integer, b_Integer} /; b == a + 1, {1}]


Remember that the output of Position is directly usable with the Extract command.

• (+1) this method work for the case when Length[z]==2. Mar 24, 2023 at 10:01