# List replacements

Sorry, for the broad title, didn't know how to best describe it. I have a list likes this:

list = {{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {{1, 2,
3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}}


And I want to replace the second part of the list elements, i.e. {4,5,6} everywhere by just the first element of this part, i.e. 4. the list should then look like this:

list2 = {{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}


I can do it with some complicated constructions looping through all the list elements by means of Table but there must be an easier way by using Replace or MapAtand I just can't figure it out.

Any help appreciated!

list2 = Replace[list, {a_, ___} -> a, {3}]
list2 = MapAt[First, list, {All, All, -1}]


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

If list is very big I think the fastest one would be

Join[Drop[list, None, None, -1], list[[All, All, {-1}, 1]], 3]

• Thanks Coolwater! Can you maybe comment on the first line that uses Replace a bit, I don't understand what exactly you did there ;). Especially this part {a_, ___}->a Commented Aug 17, 2017 at 13:45
• In the deepest level {3} we need to replace elements with the form {__} (i.e. a list with one or more elements). I write instead {a_, ___} (one element plus zero or more elements) to keep a reference only to what's needed Commented Aug 17, 2017 at 14:01
• Ah I see, thank you! Commented Aug 17, 2017 at 14:05

Also:

ClearAll[f1, f2, f3, ☺]
f1 = ReplacePart[#, {_, _, -1, 0} :> (# &)] &;
f2 = Module[{l = #}, l[[All, All, -1, 0]] = # &; l] &;
f3 = Module[{l = #}, l[[All, All, -1]] = l[[All, All, -1, 1]]; l] &;
☺ = # & @@@ {##} & @@@ # & /@ # &;   (* for fun *)

f1 @ list


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

Equal @@ (#@list & /@ {f1, f2, f3, ☺})


True

• So many solutions, thanks :)! Commented Aug 17, 2017 at 14:44
Clear["Global*"];


With another similar entry added at level 1 as an example:

list = {{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {{1, 2,
3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {1, 2, 3, {4, 5, 6}}}

Replace[list, {x__Integer, k : {y__}} :> {x, First@k}, -1]


or:

list /. {x__Integer, k : {y__}} :> {x, First@k}


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

Using Map and AtomQ:

Map[If[AtomQ[#], #, ##[[1]]] &, list, {3}]

(*{{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}*)

list =
{{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}},
{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}};


Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> Nothing, {All, All, -1, 2 ;;}] @ list /. {a_} :> a


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

Using ReplaceAll

list /. {a__Integer, b_} :> {a, b[[1]]}
`

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