# How to apply or Map a function to a 2 variables nested list

I tried to understand the mechanism of pure function tricks. Imaging I have a nested list generated by:

list=Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}]


Result:

>    {{{1, -1}, {1, 1}}, {{3, -3}, {3, -1}, {3, 1}, {3,     3}}, {{5,
> -5}, {5, -3}, {5, -1}, {5, 1}, {5, 3}, {5,     5}}, {{7, -7}, {7, -5}, {7, -3}, {7, -1}, {7, 1}, {7, 3}, {7,     5}, {7, 7}}, {{9, -9}, {9,
> -7}, {9, -5}, {9, -3}, {9, -1}, {9,     1}, {9, 3}, {9, 5}, {9, 7}, {9, 9}}}


And a function:

Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]


I want the Fun to apply to each pair of the list to calculate the sum of all the result.

Should I use something like Fun[#1,#2]&/@list ? But it never works out, idk why.Thanks for your help!

• Take a look at Mike's and Chris's answers, and notice the difference between Apply and Map, both are great tools, both can be made to work in the same situations, but usually one is more suited to the task at hand. Compare the results of f @@ {1, 2}, f @@@ {{1, 2}, {3, 4}, {5, 6}}, and f /@ {{1, 2}, {3, 4}, {5, 6}} Jan 25, 2018 at 22:05

Apply Fun at level 2 of list.

list = Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}];

Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]

Apply[Fun, list, {2}]


Why not just re-define your function to

Fun2[{x_, y_}] := Total[Sqrt[x^2 + y^2]]


then

Map[Fun2, list, {2}]


You can solve your problem as follows:

llist = Flatten[list, 1]
Apply[Fun, llist, 1]


If the structure of list should be kept

Table[Apply[Fun, list[[i]], -1], {i, 1, Length[list]}]


If you wish to keep the structure of the list you can do something like

In[1]:= list = Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}];

In[2]:= Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]

In[3]:= Map[Fun @@ # &, list, {2}]

Out[3]= {{5/2, 5/2}, {3 + Sqrt[2], 21/2, 21/2,
3 + Sqrt[2]}, {5 + Sqrt[2], 69/2, 53/2, 53/2, 69/2,
5 + Sqrt[2]}, {7 + Sqrt[2], 149/2, 117/2, 5 + Sqrt[2], 5 + Sqrt[2],
117/2, 149/2, 7 + Sqrt[2]}, {9 + Sqrt[2], 261/2, 213/2,
3 + Sqrt[10], 165/2, 165/2, 3 + Sqrt[10], 213/2, 261/2,
9 + Sqrt[2]}}