# Modify list elements if last two entries are equal

Suppose I have a list as follows

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}}


and I want to check the last two coordinates are equal or not. If that is the case then I want it to print out T after that list. So the result should be

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1,T}}


I am thinking about using "if" but I have no idea how to do it.

• Try: (Append[#, If[#[[-1]] == #[[2]], "T", Nothing]]) & /@ {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}} Commented May 11, 2022 at 9:13
• Yes, you are right! Thank you. Commented May 11, 2022 at 19:40

I think the most expressive would be to use Replace:

list = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};
Replace[
list,
{rest___, l_, l_} :> {rest, l, l, T},
1
]
(* {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}} *)


Some alternatives:

Replace[list, list : {___, l_, l_} :> Append[list, T], 1]
Replace[list, l_ /; Equal @@ l[[-2 ;;]] :> Append[l, T], 1]
Replace[list, {list : PatternSequence[___, l_, l_]} :> {list, T}, 1]
Map[If[Equal @@ #[[-2 ;;]], Append[#, T], #] &, list]
Map[If[#[[-2]] == #[[-1]], Append[#, T], #] &, list]
Map[If[Equal @@ #[[-2 ;;]], Append[T], # &]@# &, list]

alist = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}}

Join @@@ Transpose[{#,
List /@ Equal @@@ #[[All, -2 ;; -1]]}] /. {False -> Nothing,
True -> T} & @alist


A simpler version of the above:

# ~ Join ~ If[Equal @@ #[[-2 ;; -1]], {T}, {Nothing}] & /@ alist


Description: Take a sublist (#) and Join an item with it. The item will be T if the last two entries are Equal, else Nothing. Map (/@) this over the entire list.

Result:

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}

list = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};


Using SequenceReplace (new in 11.3) and Splice (new in 12.1)

SequenceReplace[list, {a : {__, x_, x_}} :> {Splice @ a, T}]


{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}

Using function deconstruction

f[a:{__, x_, x_}] := {Splice @ a, T}

f[a_] := a

f /@ list


{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}

A = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};


Another way:

 Map[If[Mean[#[[-2 ;; -1]]] === #[[-1]], Append[#, T], #] &, A]


{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}

If your data is always a list of lists and you always want the transformation performed at that second level, then this works (I've named your data theData):

Replace[theData, {head___, t_, t_} :> {head, t, t, "T"}, 1]

list = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};


Another way using Take:

If[Equal @@ Take[#, -2], Append[#, T], #] & /@ list


{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}

Or using ReplaceAll:

list /. s : {__, a_, b_} /; Equal @@ {a, b} :> Append[T]@s


{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}