# Manipulating a list while maintaining the nested list structure

Suppose I have a list of pairs of complex numbers with nesting as follows

{
{{1.91885 + 0.09170475 I, 1.91901 + 0.0629745061 I},
{1.91837 + 0.092182 I, 1.9189 + 0.063 I},
{1.9837 + 0.2182 I, 1.99 + 0.063 I},
{1.91837 + 0.0921 I, 1.89 + 0.3 I}},
{{1.91 + 0.091 I, 1.91 + 0.062974 I},
{1.918 + 0.092 I, 1.89 + 0.63 I},
{1.915 + 0.0915 I, 1.9191 + 0.05061 I}
}
}


In reality, the list I am working with has many more sublists (here I've just shown two) and many more elements in each sublist.

I am trying to extract the second component of each pair of complex numbers while maintaining the nesting so here the expected output would be

{{1.91901 + 0.0629745061 I, 1.9189 + 0.063 I, 1.99 + 0.063 I,1.89 + 0.3 I},
{1.91 + 0.062974 I, 1.89 + 0.63 I,  1.9191 + 0.05061 I}}


I have tried defining a function sec[z_]:=Part[z,2] and using Map or Apply to get what I want but this doesn't seem to work. Is there a way to do this?

• Closely related question Nov 5, 2020 at 5:26

Try this:

lst = {{{1.91885 + 0.09170475 I,
1.91901 + 0.0629745061 I}, {1.91837 + 0.092182 I,
1.9189 + 0.063 I}, {1.9837 + 0.2182 I,
1.99 + 0.063 I}, {1.91837 + 0.0921 I,
1.89 + 0.3 I}}, {{1.91 + 0.091 I,
1.91 + 0.062974 I}, {1.918 + 0.092 I,
1.89 + 0.63 I}, {1.915 + 0.0915 I, 1.9191 + 0.05061 I}}};

Map[ReplaceAll[#, {x_, y_} -> y] &, lst]

(*  {{1.91901 + 0.0629745 I, 1.9189 + 0.063 I, 1.99 + 0.063 I,
1.89 + 0.3 I}, {1.91 + 0.062974 I, 1.89 + 0.63 I,
1.9191 + 0.05061 I}}   *)


Have fun!

• Thanks Alexei! I always forget about using ReplaceAll.
– math
Nov 4, 2020 at 10:58

Here is simpler way to do it with ReplacePart. No need to use Map. Like so:

ReplacePart[lst, {i_, j_} :> lst[[i, j, 2]]]

{{1.91901 + 0.0629745061 I, 1.9189 + 0.063 I, 1.99 + 0.063 I, 1.89 + 0.3 I},
{1.91 + 0.062974 I, 1.89 + 0.63 I, 1.9191 + 0.05061 I}}

• I ran some AbsoluteTiming experiments using this method and Alexei's. I found on my sample list Alexei's method took around 950 seconds, but ReplacePart didn't finish running even after letting it run for around a day. Are there some limitation with the ReplacePart method to be aware of?
– math
Nov 10, 2020 at 9:33
• @math. I don't have any idea why ReplacePart is running so slowly on your system. You don't describe your test in sufficient detail. I timed my code on this array: data = With[{rows = 1000, cols = 1000}, RandomComplex[1 + I, {rows, cols, 2}]]; and it completed in 2.3 sec. That seems pretty fact to me. Nov 11, 2020 at 7:59

Just this,

l //. {a___, {b_, c_}, d___} :> {a, c, d}


Where l is your list.