# Manipulating a list to make it nested

I have a long list, where the elements are of this kind {x,y,g,a1,a2,a3} and I want to extract some sublists with which I can make plots or manipulate the elements.

For instance, if I want to make a ContourPlot that has x and y as the cartesian axes and g as the "third" axis that creates the contour, I would really love to have my entries rearranged in a nested way as {{x,y},g}, from which I could easily create an InterpolatingFunction like:

newlistTEMP = Interpolation[nestedlist, InterpolationOrder->2];
gfunc[x_,y_] := newlistTEMP[x,y];


However, I am failing at finding a clever way to rearrange the elements of my list into the desired nested list form. The best I can do is to extract a sublist like:

sublist = Cases[list, {x_, y_, g_, _, _, _} :> {x, y, g}];


but after this I am stuck.

• I don’t understand the problem, I’m afraid. Can you just put {{x, y}, g} on the right hand-side in Cases? Jan 31, 2021 at 21:28
• Or data2 = {#[[1 ;; 2]], #[]} & /@ data Jan 31, 2021 at 21:29
• @C.E. no, it does not give a nested list.
– Lele
Jan 31, 2021 at 22:01
• @Lele I posted my approach as an answer with an output example, in case we are simply talking past each other. If that output is not what you mean by nested list, please explain what you mean by nested list. Jan 31, 2021 at 22:44

{x, y, g, a, b, c} /. {x_, y_, g_, next___} :> f1[{{x, y}, g}, f2@next]


and replace f1, f2 by whatever you need.

Here is one way:

list = ConstantArray[Range, 10];
Cases[list, {x_, y_, g_, _, _, _} :> {{x, y}, g}]


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

• Ok, this does the trick. It didn't work in the first place for an error of mine. However, when I try to interpolate the data, it returns this error message: Interpolation::udeg: Interpolation on unstructured grids is currently only supported for InterpolationOrder->1 or InterpolationOrder->All. Order will be reduced to 1. This is strange, usually it should be possible to create a function that interpolates the coordinates {{x1,y1},f[x1,y1]}, {{x2,y2},f[x2,y2]}, ... with the interpolation order that I wish.
– Lele
Feb 1, 2021 at 8:21